hi i am trying to detect if usb connect to client side. what my logic is that to get the total number of disks if new disk added means new devices is added on client if usb remove from client means devices is remove from client so i keep checking in loop the client show total = 1 or total = 2 , 1 means only 1 disk is available 2 means new device is added and so on. It working fine but the sock.send("Device Added in " + username) sock.send("Device remove in " + username) these command not working i dont get these message on server side if i plug or plug out the usb from client side. i am not sure if my if else conditions are correct or not.
os linux
this is client side code
from socket import *
import os, string, time
import getpass
host = 'localhost'
port = 52000
username = getpass.getuser()
sock = socket()
# Connecting to socket
sock.connect((host, port)) # Connect takes tuple of host and port
def detect_device(previous):
total = os.system(' lsblk | grep disk | wc -l')
time.sleep(3)
# if conditon if new device add
if total<previous:
sock.send("Device Added in " + username)
# if no new device add or remove
elif total==previous:
detect_device(previous)
# if device remove
else:
sock.send("Device Removed in " + username)
# Infinite loop to keep client running.
while True:
data = sock.recv(1024)
if (data == 'Hi'):
while True:
detect_device(os.system(' lsblk | grep disk | wc -l'))
sock.close()
output i get on client side is
1 1 1 2 2 2 2 1 1
1 means current number of total disks are 1 if i plug usb then total number of disks is 2 then 1 means i disconnect USB
ok i fixed it out the os.system return 0 in output so i try it with subprocess.run and it runs fine.
Related
hi i create server client model in which client keep checking if new device add or not and send response to server side its working fine what i want to display the response i get from client to server on web browser continuously using flask or Django.
this is my client code
from socket import *
import subprocess, string, time
host = 'localhost' # '127.0.0.1' can also be used
port = 53000
sock = socket()
# Connecting to socket
sock.connect((host, port)) # Connect takes tuple of host and port
def detect_device(previous):
import socket
username2 = socket.gethostname()
ip=socket.gethostbyname(username2)
total = subprocess.run('lsblk | grep disk | wc -l', shell=True, stdout=subprocess.PIPE).stdout
time.sleep(3)
# if conditon if new device add
if total>previous:
response = "Device Added in " + username2 + " " + ip
sock.send(response.encode())
# if no new device add or remove
elif total==previous:
detect_device(previous)
# if device remove
else:
response = "Device Removed in " + username2 + " " + ip
sock.send(response.encode())
# Infinite loop to keep client running.
while True:
data = sock.recv(1024)
if (data == b'Hi'):
while True:
detect_device(subprocess.run(' lsblk | grep disk | wc -l', shell=True , stdout=subprocess.PIPE).stdout)
sock.close()
this is my server side code
from socket import *
# Importing all from thread
import threading
# Defining server address and port
host = 'localhost'
port = 53000
# Creating socket object
sock = socket()
# Binding socket to a address. bind() takes tuple of host and port.
sock.bind((host, port))
# Listening at the address
sock.listen(5) # 5 denotes the number of clients can queue
def clientthread(conn):
# infinite loop so that function do not terminate and thread do not end.
while True:
# Sending message to connected client
conn.send('Hi'.encode()) # send only takes string
data =conn.recv(1024)
print (data.decode())
while True:
# Accepting incoming connections
conn, addr = sock.accept()
# Creating new thread. Calling clientthread function for this function and passing conn as argument.
thread = threading.Thread(target=clientthread, args=(conn,))
thread.start()
conn.close()
sock.close()
this is output on server side
Device Added in wraith 192.168.10.9
Device Removed in wraith 192.168.10.9
i need to display this output on web page .
Flask and Django are Web application frameworks that are designed for the HTTP protocol, but you're using the low-level socket library and basically not using any established protocol. If you want to use Flask/Django because you want to have a broadcasting platform for the results of your device-watching client-side script, then I recommend that instead of socket, use requests (link) in your client script to send an HTTP POST request to your Flask/Django Web app. As for how to build the app, well there are tutorials for that. I do want to note that the minimalist Flask is probably a better fit for this project than the more opinionated Django framework.
I developed an application to wakeOnLan (WOL) and is working fine with in same series of IP addresses.
My problem is i am not able to wakeOnLan where systems are on on other series of IP address on Same Network.
For EX:
My system A is having IP 172.16.46.76,
I am able to wake any system C with Ip Address 172.16.46.13, and also able to wake on lan any system with in the range of 172.16.46.1 to 172.16.45.254 using BroadCast address 1721.16.46.255
But when i run same application from other system B having IP 172.16.51.26, I am not able to wakeOnLan systems C with IP Address 172.16.46.13
I checked using WakeOnLan monitor to confirm if system C is receiving magic packet. And it is receiving from system A but not from system B. I could able to ping system C from both system A and system B
Can any one suggest me solution where is am doing wrong. I code is give below for your reference.
import sys, struct, socket
# Configuration variables
broadcast = ['172.16.46.255','172.16.51.255']
wol_port = 9
known_computers = {
'mercury' : '00:1C:55:35:12:BF',
'venus' : '00:1d:39:55:5c:df',
'earth' : '00:10:60:15:97:fb',
}
def WakeOnLan(ethernet_address):
# Construct 6 byte hardware address
add_oct = ethernet_address.split(':')
if len(add_oct) != 6:
print "\n*** Illegal MAC address\n"
print "MAC should be written as 00:11:22:33:44:55\n"
return
hwa = struct.pack('BBBBBB', int(add_oct[0],16),
int(add_oct[1],16),
int(add_oct[2],16),
int(add_oct[3],16),
int(add_oct[4],16),
int(add_oct[5],16))
# Build magic packet
msg = '\xff' * 6 + hwa * 16
# Send packet to broadcast address using UDP port 9
print msg
soc = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
soc.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST,1)
for i in broadcast:
soc.sendto(msg,(i,wol_port))
soc.close()
def wol(*argv):
if len(argv) == 0:
print "\n*** No computer given to power up\n"
print "Use: 'wol (computername)' or 'wol (00:11:22:33:44:55)'"
else:
for i in argv:
if i[0] != '/':
if ":" in i:
# Wake up using MAC address
print 'waking using MAC %s' % i
WakeOnLan(i)
else:
# Wake up known computers
if i in known_computers:
WakeOnLan(known_computers[i])
else:
print "\n*** Unknown computer " + i + "\n"
quit()
if len(argv) == 1:
print "\nDone! The computer should be up and running in a short while."
else:
print "\nDone! The computers should be up and running in a short while."
print
wol('xx:xx:xx:xx:xx:xx')
A snapshot from Wake On Lan Monitor.
Two things you can check.
You're trying to send a broadcast packet from one subnet to another. This implies a network device inbetween the two, probably a router. Routers are normally configured to disallow broadcast packets between their managed subnets to avoid a broadcast storm.
If this is your own experimental network on which you own the routers then you'll be able to go in and change the router configuration yourself.
If you've done (1) and it still doesn't work then look at the TTL of the packets you're generating. If they're being sent with a TTL of one (often the default for broadcast/multicast for safety reasons) then you'll need to increase it by one for each network device that you must traverse along the way because each device decrements the TTL and drops the packet if zero is reached.
I want to know these for I am getting crazy with this:
How can I do these:
1-If the server terminates the clients should terminate also. Your server should allow the administrator to close all connections (i.e. the server must wait for the user to terminate the program preferably through a menu interface)
2-In order to know the number of clients connected you will need to identify each client uniquely – this can be accomplished by using the pid that is uniquely assigned for each client connection (store these in a global list). These connections can change dynamically (i.e. clients can disconnect and reconnect) so you must maintain this list on the server.
This is my server side code:
Thanks in advance
import _thread
import socket
import sys
from datetime import datetime
def serveclient(c):
global v, nclient, vlock, nclientlock
while(True):
k=(c.recv(1)).decode('utf-8')
if(k==''):
break
if(k=='D'):
today = str(datetime.now().strftime('%Y-%m-%d'))
c.send(today.encode('utf-8'))
if(k=='T'):
tme = str(datetime.now().strftime('%H:%M:%S'))
c.send(tme.encode('utf-8'))
if(k=='X'):
<<<< # Here I should put the number of clients connected and echo back the number like the above code
vlock.acquire()
v+=k
vlock.release()
#Echo back
c.send(v.encode('utf-8'))
c.close() #End connection
nclientlock.acquire()
nclient-=1
nclientlock.release()
#Main driver code
listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
port = int(sys.argv[1])
listener.bind(('',port))
listener.listen(5)
#Initialize global data
v=''
vlock=_thread.allocate_lock()
nclient=10 #Max number of clients
nclientlock=_thread.allocate_lock()
#accept calls from clients
for i in range(nclient):
(client, ap) = listener.accept()
_thread.start_new_thread(serveclient, (client,))
listener.close()
while nclient >0:
pass #do nothing, just wait for client count to drop to zero
print('The final string is: ', v)
<<<<<<<<<<<<<<<<<<<<<<<<<This the Client Code>>>>>>>>>>>>>>>>>>>>>>>
#Client Program. Sends a single char at a time to the server until the client
#sends a '', this will terminate the client.
#
#usage: python server port
import socket
import sys
#create the socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = sys.argv[1] #Server info from cmd line
port = int(sys.argv[2]) #Port from cmd line
#Conncet to server
s.connect((host, port))
while(True):
#get letter
k = input('enter a letter: ')
s.send(k.encode('utf-8'))
if(k==''):
break
v=s.recv(1024) #receive upto 1024 bytes
print(v.decode('utf-8'))
s.close()
Just increment a count every time you accept a socket, and decrement it every time you close an accepted socket.
Am newbie to python and stuck at a point. I want to create port scanner with using only python 3 inbuilt libraries (means avoiding scapy etc) I have following code :
import socket
for i in range(1,26):
s = socket.socket()
s.settimeout(0.5)
ip = "74.207.244.221" #scanme.nmap.org
response = s.connect_ex((ip, i))
if response:
print ("%d\tclose" %i)
else:
print ("%d\topen" %i)
s.close()
Now I want to add 2 functionalities to this : that is
Distinguish between close and filtered ports . In both cases am receiving same errno in return so how can I check if I have received back a rst packet or nothing ? As far as I have tried s.recv() isn't working for this.
I want to control the number of tries (attempts), i.e I want to send only one or two syn packets. I don't want this program to send more than 2 syn packets for probes. How can this thing be achieved ?
Distinguish between close and filtered ports . In both cases am
receiving same errno in return so how can I check if I have received
back a rst packet or nothing
You've probably only checked with servers that send back a RST. Here's what I tried:
First case, normal config:
>>> os.strerror(s.connect_ex((ip, 81)))
'Connection refused'
Second, with manual iptables:
iptables -A OUTPUT -p tcp --dport 81 -j DROP
>>> os.strerror(s.connect_ex((ip, 81)))
'Resource temporarily unavailable'
I want to control the number of tries (attempts), i.e I want to send
only one or two syn packets.
I don't think there's a setsockopt TCP option exposed, but on linux there's:
net.ipv4.tcp_syn_retries
However, since you limited the timeout for the socket, all operations that don't finish within 0.5 seconds will time out. So it's likely only 1 or 2 SYNs will leave the station.
#!/usr/bin/python
import socket
s = socket.socket(socket.AF_INET, socekt.SOCK_STREAM)
host = 74.207.244.221
def portscan(port):
try:
s.connect((host,port))
return True
else:
return False
for x in range(1,255):
if portscan(x):
print('Port',x,'Is Open')
A while ago, I wrote [with some help from Google] a small WOL script to switch on the computers in my network. Here is the script:
exec /usr/bin/python -x "$0" "$#"
#
node_lst = [
'srv1 0a:1b:8c:0d:2e:7f',
'srv2 0A-0B-4C-8D-CE:3F',
]
#
import os,sys,string,commands
import struct, socket
import re,random
retval = 0
mac_addr = "mac_addr.txt"
X = '([a-zA-Z0-9]{2}[:|\-|.]?){5}[a-zA-Z0-9]{2}'
S = re.compile(r'\s+')
mmap = {}
## First argument 'None' in str.translate is new in 2.6.
## Previously, it was a string of 256 characters
if sys.version_info < (2, 6):
f1_arg = ''.join(chr(i) for i in xrange(256))
else:
f1_arg = None
## broadcast address
sysOS = "uname -s"
BSD = "ifconfig | grep -w broadcast | cut -d\ -f 6"
LNX = "ip -o addr show | grep -w inet | grep -e eth | cut -d\ -f 9"
#
if commands.getoutput(sysOS) == "Linux":
bCast = commands.getoutput(LNX)
elif commands.getoutput(sysOS) == "Darwin":
bCast = commands.getoutput(BSD)
else:
print "System not supported!!"
sys_exit()
def WakeOnLan(mac_address):
## Building the Wake-On-LAN "Magic Packet"...
## Pad the synchronization stream.
data = ''.join(['FFFFFFFFFFFF', mac_address * 20])
msg = ''
## Split up the hex values and pack.
for i in range(0, len(data), 2):
msg = ''.join([msg, struct.pack('B', int(data[i: i + 2], 16))])
## ...and send it to the broadcast address using UDP
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
s.sendto(msg, (bCast, 9))
s.close()
def sys_exit():
sys.stdout.flush()
sys.exit(1)
## check if hostname is provided
if len(sys.argv) != 2:
print "Usage: %s <hostname>" % sys.argv[0]
sys_exit()
for i in node_lst:
# strip off everything from first "#" [if] found
i = i.split('#',1)[0]
if not re.search(X, i):
continue
h = S.split(i,1)[0] ## host name
m = S.split(i,1)[-1] ## MAC address
mmap[h] = m.strip('\t|" "')
for j, k in mmap.iteritems():
if sys.argv[1] == j:
if not re.search(X.replace('zA-Z','fA-F'), k):
print "Invalid MAC address [",k,"]; nothing to do!!"
sys_exit()
else:
WakeOnLan(k.translate(f1_arg,':.-'))
print "WOL request has been sent to %s [%s]" % (j,k)
break
else:
print "Host [%s] doesn't exist!!" % sys.argv[1]
sys_exit()
Which works just fine from inside my home network (or LAN). How can I change the script to make it work for outside of my LAN? Any idea or suggestions? Cheers!!
This is not possible because WOL packets are broadcast packets (since you can't know who to send it too). Home routers and especially ISP/Network routers discard all broadcast packets because else everytime you run this one script all the computers on the entire internet would receive your package, which would cause quite some clutter.
What you of course can do is write a small application that is on a computer that is running inside the WAN in which you wish to turn on all computers, and then have that application send a WOL packet. However this would require a computer with internet access to be turned on at all times.
Configure your router to forward packets on a selection of 10 non-sequential ports to a machine on your LAN.
Devise some scheme based on say GMT Time + a hash to generate the port trigger sequence.
Have a python program (use scappy) on your command box inside that network listen for a series of syn packets.
The listener code would be analogous to the following tcpdump syntax:
sudo tcpdump -ni eth0 'tcp[tcpflags] & (tcp-syn) !=0'
Where it captures just syn packets.
Your program just sits there, waiting for the right syn sequence. When it receives the sequence, it runs your WOL script.
Done.
If you don't want to open ports, your script could instead poll a remote website, waiting for changes. Or listen for email fetched via email.
Taking your idea further, you could do fancy stuff like turn on your lights or boot up the TV.