I'm new to python and I'm trying to ping my office network and trying to get the hostnames for an inventory system I'm trying to build for work. When I run the script below, I get the IP Address and get either Online or Offline, but I don't get the correct hostname. I only get the hostname of the computer sending out the ping. I think I need to capture it with a string but not sure how to do that. Ultimately this will be run in a GUI with the push of a button.
import ipaddress
from subprocess import PIPE, Popen
import socket
network = ipaddress.ip_network('192.168.1.0/24')
for i in network.hosts():
i = str(i)
h = socket.gethostname()
toping = Popen(['ping', '-c', '5', '-w', '100', i], stdout=PIPE)
output = toping.communicate()[0]
hostalive = toping.returncode
if hostalive == 0:
print(i)
print(h)
print("Is Online")
else:
print(i)
print("Is Offline")
Related
I am able to execute the client-server programs in Python IDLE and in PyCharm but I am stuck while executing the same program on Google Colab.
The sample server code is:
s = socket.socket()
print("Socket Created")
s.bind(('localhost',9999))
s.listen(3)
print("Waiting for a Connection !!")
while True:
c, addr = s.accept()
name = c.recv(1024).decode()
print("Connected with :",addr, " ", name)
c.send(bytes("Welcome to Socket Programming",'utf-8', name))
c.close()
The sample client code is:
c = socket.socket()
c.connect(('localhost', 9999))
name = input("Enter your name: ")
c.send(bytes(name,'utf-8'))
print(c.recv(1024).decode())
On Google Colab, I pasted these codes in different notebooks and ran the server code first. I got the following error:
<ipython-input-1-0b55cff963bc> in <module>()
1 import socket
2 c = socket.socket()
----> 3 c.connect(('localhost', 9999))
4
5 name = input("Enter your name: ")
ConnectionRefusedError: [Errno 111] Connection refused
Then, I pasted the client code in the same notebook but in different code shells then I am not getting any output. Even after searching on Google, I am not able to find the solution to my problem. What wrong am I doing?
I want to monitor a server using AWS Lambda function with Python 3.9 version.
I'm using ping test connection and here's my code
import subprocess
import platform
def lambda_handler(event, context):
SERVERS = [
('203.124.136.164', 'Local Host 1')
]
for (server, name) in SERVERS:
check_connection(server, name)
def check_connection(server, name):
if ping(server):
print("%s is UP" % (name))
else:
print("%s is DOWN" % (name))
def ping(server):
try:
output = subprocess.check_output("ping -{} 1 {}".format('n' if platform.system().lower() == "windows" else 'c', server ), shell=True, universal_newlines=True)
if 'unreachable' in output:
print('unreachable')
return False
elif 'timed out' in output:
print('timed out')
return False
else:
print('success')
return True
except Exception as err:
print("An error occurred: %s" % (err.__str__()))
return False
But I got an error:
/bin/sh: ping: command not found
An error occurred: Command 'ping -c 1 203.124.136.164' returned non-zero exit status 127.
Why I got that error and what is the right implementation to monitor a server using IP?
I'm just a beginner. Please help!
Disclaimer: the IP provided on the code is just dummy.
I think AWS Lambda doesn't allow for ICMP to go outbound. It only allows for TCP or UDP outbound so since ping is neither it doesn't work. Even if you try to make a custom layer and import to Lambda you will get a permissions error since ICMP is not allowed.
Sorry my friend, the easiest work around I believe would to make a T1.micro to run the full python code.
I am creating a TCP server on raspberry pi so that i can control it from my android phone over WIFI. I have connected both the pi and the phone to my WIFI router.
import socket
from cookieLED_FINAL import callLED
host = '192.168.100.100'
port = 5560
def setupServer():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("Socket created.")
try:
s.bind((host, port))
except socket.error as msg:
print(msg)
print("Socket bind complete.")
return s
def setupConnection():
s.listen(1) # Allows one connection at a time.
conn, address = s.accept()
print("Connected to: " + address[0] + ":" + str(address[1]))
return conn
def storeFile(filePath):
picFile = open(filePath, 'wb')
print("Opened the file.")
pic = conn.recv(1024)
while pic:
print("Receiving picture still.")
picFile.write(pic)
pic = conn.recv(1024)
picFile.close()
def dataTransfer(conn):
# A big loop that sends/receives data until told not to.
while True:
# Receive the data
data = conn.recv(1024) # receive the data
data = data.decode('utf-8')
# Split the data such that you separate the command
# from the rest of the data.
dataMessage = data.split(' ', 1)
command = dataMessage[0]
if command == 'GET':
reply = GET()
elif command == 'REPEAT':
reply = REPEAT(dataMessage)
elif command == 'STORE':
print("Store command received. Time to save a picture")
storeFile(dataMessage[1])
print("FINISHED STORING FILE")
break
elif command == 'LED_ON':
callLED()
reply = 'LED was on'
elif command == 'EXIT':
print("Our client has left us :(")
break
elif command == 'KILL':
print("Our server is shutting down.")
s.close()
break
else:
reply = 'Unknown Command'
# Send the reply back to the client
conn.sendall(str.encode(reply))
print("Data has been sent!")
conn.close()
s = setupServer()
while True:
try:
conn = setupConnection()
dataTransfer(conn)
except:
break
When using IP:
192.168.100.100 :
[Errno 99] Cannot assign requested address
127.162.100.100 or 0.0.0.0: The socket is being created but android client is not getting connected.
On my android phone i am using an app named TCP/UDP Test Tool which I downloaded from play store.
I am new on linux as well as on raspberry pi 3 B+.
OS: RASPBIAN
PROGRAMMING LANGUAGE: PYTHON 3.5
Download a software named Advanced IP Scanner.
Connect all the devices to the same network i.e Access point.
On the raspberry pi open terminal and type ifconfig get the ipv4 not the 0.0.0.0 or the 127.0.0.1 the other one.
For example if the ip is showing 192.168.100.144 then input 192.168.100.1-255 in Advanced IP scanner in windows start the scan and find the ips that has your raspberry pi's name written in it. Now input these ips in the tcp client and connect.
I'm working on a project and I want to use RFID as a position reference(when raspberry pi and MFRC522 read the data, send it to server and make sure where is the position or adjust position while RFID reader is fixed)
My code is below:
import RPi.GPIO as GPIO
import MFRC522
import signal
import socket
HOST = '192.168.11.48'
PORT = 9009
continue_reading = True
# Capture SIGINT for cleanup when the script is aborted
def end_read(signal,frame):
global continue_reading
print("Ctrl+C captured, ending read.")
continue_reading = False
GPIO.cleanup()
# Hook the SIGINT
signal.signal(signal.SIGINT, end_read)
# Create an object of the class MFRC522
MIFAREReader = MFRC522.MFRC522()
# Welcome message
print("Welcome to the MFRC522 data read example")
# This loop keeps checking for chips. If one is near it will get the UID and authenticate
with socket.socket(socket.AF_INET,socket.SOCK_STREAM) as sock:
sock.connect((HOST,PORT))
#print("closing client")
while True:
while continue_reading:
# Scan for cards
(status,TagType) = MIFAREReader.MFRC522_Request(MIFAREReader.PICC_REQIDL)
# If a card is found
if status == MIFAREReader.MI_OK:
print("Card detected")
# Get the UID of the card
(status,uid) = MIFAREReader.MFRC522_Anticoll()
# If we have the UID, continue
if status == MIFAREReader.MI_OK:
# Print UID
print("Card read UID: "+str(uid[0])+","+str(uid[1])+","+str(uid[2])+","+str(uid[3]))
# This is the default key for authentication
key = [0xFF,0xFF,0xFF,0xFF,0xFF,0xFF]
# Select the scanned tag
MIFAREReader.MFRC522_SelectTag(uid)
# Authenticate
status = MIFAREReader.MFRC522_Auth(MIFAREReader.PICC_AUTHENT1A, 8, key, uid)
data = "str(uid[0])"
msg = data
sock.sendall(msg.encode())
data = sock.recv(128)
print('date from Echo server is [%s]'%data.decode())
# Check if authenticated
if status == MIFAREReader.MI_OK:
MIFAREReader.MFRC522_Read(8)
MIFAREReader.MFRC522_StopCrypto1()
else:
print("Authentication error")
I am using echo server to make sure that it's working
code for echo server is:
import socketserver
HOST = ''
PORT = 9009
class MyTcpHandler(socketserver.BaseRequestHandler):
def handle(self):
print("[%s]conneted"%self.client_address[0])
try:
while True:
self.data = self.request.recv(1024)
if self.data.decode() == "/quit":
print('ended by user [%s]'%self.client_address[0])
return
print('[%s]'%self.data.decode())
self.request.sendall(self.data)
except Exceptions as e:
print(e)
def runServer():
print("starting echo server")
print("if you want to close echo server, click Ctrl+C")
try:
server = socketserver.TCPServer((HOST,PORT), MyTcpHandler)
server.serve_forever()
except KeyboardInterrupt:
print("--- closing server")
runServer()
I ran fist piece of code while the second one was running, but only result I got was -
Welcome to the MFRC522 data read example
Card detected
Card read UID:178,29,209,48
size:8.
Anyone had idea what I should change to make it work?
thanks
i need to send a packet using scapy to a dns server i made, and for some reason the server doesnt get the packet
this is the dns server
-- coding: utf-8 --
from scapy.all import *
def le_check(p):
return (DNS in p and p[0][DNSQR].qtype == 1 and p[0][UDP].dport==53)
def main():
data_base = {'www.google.com': ('172.217.23.164','173.194.79.104','173.194.79.99')}
p1=sniff(count=1, lfilter=le_check)
x=p1[0][DNSQR].qname
if x in data_base:
list=data_base[x]
else:
list= "no such name"
print p1[0][DNSQR].qname
print list
send(IP(dst=p1[0][IP].src)/UDP(sport=53, dport=53)/Raw(list))
if __name__ == '__main__':
main()
code from scapy
sendp(IP(dst=MY_IP)/UDP(sport=24601,dport=53)/DNS(qdcount=1,rd=1)/DNSQR(qname="www.google.com",qtype=1))