Connecting to a wifi network using python - python

I have this code that is supposed to connect to wifi using a given ESSID and password. Here is the code:
def wifi_connect(essid, password):
# Connect to the wifi. Based on the example in the micropython
# documentation.
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print('connecting to network ' + essid + '...')
wlan.connect(essid, password)
# connect() appears to be async - waiting for it to complete
while not wlan.isconnected():
print('waiting for connection...')
print('checking connection...')
print('Wifi connect successful, network config: %s' % repr(wlan.ifconfig()))
else:
# Note that connection info is stored in non-volatile memory. If
# you are connected to the wrong network, do an explicity disconnect()
# and then reconnect.
print('Wifi already connected, network config: %s' % repr(wlan.ifconfig()))
At first, I got an error message that network was not installed. This was fixed by simply using pip to install network. After I ran this again, it told me that network has no attribute WLAN. How do I fix this? What am I doing wrong?

You are trying to run code designed for the MicroPython language, and it won't work on CPython (the Python version you'd download from Python.org or find installed on most PCs and servers).
MicroPython is designed to run on embeddable specialist hardware, and comes with its own library to support the hardware it is running on, including a network module:
To use this module, a MicroPython variant/build with network capabilities must be installed. Network drivers for specific hardware are available within this module and are used to configure hardware network interface(s).
It tells you so in the comments at the top:
# [...] Based on the example in the micropython
# documentation.
The code can't run on 'regular' CPython. You installed the PyPI network project, which is a very different module, originally designed to help learn coding for the Raspberry PI.
What project could work depends on your operating system (OS). Different OSes use different programming interfaces to let programs change networks. Most have command line tools to let you do this, which should be easy to drive from Python with the subprocess module:
Windows has the netsh command, run netsh wlan connect name=... to connect to a network interface
Mac OS X has the networksetup command, networksetup -setairportnetwork en1 ... connects you to a given WIFI network.

On a PC, you don't need network.py to connect to a Wifi access point as in ESPP32.
You connect normally by OS network connection.
The only library you need is socket. Here an example of code to get data !
import socket
def http_get(url, port):
_, _, host, path = url.split('/', 3)
addr = socket.getaddrinfo(host, port)[0][-1]
s = socket.socket()
s.connect(addr)
s.send(bytes('GET /%s HTTP/1.0\r\nHost: %s\r\n\r\n' % (path, host), 'utf8'))
while True:
data = s.recv(100)
if data:
print(str(data, 'utf8'), end='')
else:
break
s.close()
http_get('http://micropython.org/ks/test.html',80)
http_get('http://towel.blinkenlights.nl/',23)

Related

How to implement ARP ping with Scapy?

I've been trying to create a network scanner similar to netdiscover. I used Python and Scapy module to do that. I'm running my script on Kali linux on virtual box and when I'm scanning my NAT network created by Virtual Box it's showing me devices that are connected, but when I'm using wireless adapter to scan my wifi network the scanner is unable to find any devices, which is strange because netdiscover finds tons of them. However when I'm using arping function implemented by Scapy, devices are also showing, but when I'm running my code it doesn't detect any devices. Why is that?
I used code suggested by Scapy documentation and it's still not showing any devices. Only Scapy arping function detects any devices at all
import scapy.all as scapy
import subprocess as sub
import re
def get_IP():
output=sub.check_output("route -n",shell=True)
ips={}
for row in output.split("\n")[2:]:
found=re.findall("\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}",row)
device=re.findall("[a-z]{2,10}\d$",row)
for ip in found:
if ("0.0.0" not in ip and "255.255.255" not in ip):
ips[device[0]]=ip
for device,ip in ips.items():
print("Device: {}\tIP: {}".format(device,ip))
device = raw_input("Choose a device > ")
return(ips[device][:-1]+"1/24")
def scan(ip):
#My code
print("Scanning...")
arp_request=scapy.ARP(pdst=ip)
brodcast=scapy.Ether(dst="ff:ff:ff:ff:ff:ff")
arp=brodcast/arp_request
answered=scapy.srp(arp, timeout=1,verbose=False)[0]
for element in answered:
print("IP:{}".format(element[1].psrc))
print("MAC address: {}\n".format(element[1].hwsrc))
def scan2(ip):
#Code from scapy documentation and it's also not detecting any devices
ans, unans = scapy.srp(scapy.Ether(dst="ff:ff:ff:ff:ff:ff")/scapy.ARP(pdst=ip),timeout=2)
ans.summary(lambda (s,r): r.sprintf("%Ether.src% %ARP.psrc%") )
def scan3(ip):
#This works
scapy.arping(ip)
ip = get_IP()
scan(ip)
scan2(ip)
scan3(ip)
I solved it just by deactivating connection to NAT Network, so I used ifconfig eth0 down. However in some cases it's not the problem. If you're router does not allow net scans you need to change you're MAC address which means that you need to run series of these commands
ifconfig wlan0 down
ifconfig wlan0 hw ether 00:22:44:66:88:33 # Ofcourse you can choose any MAC address you want
ifconfig wlan0 down
ifconfig wlan0 up
service network-manager restart
After that network scanner will detect devices that are currently in the network
Try this way :
from scapy.all import scapy,ARP,Ether,srp,arping
or this way:
from scapy.layers.l2 import *
In both cases remember delete the "scapy.", like this:
#Before
scapy.arping(ip)
#After
arping(ip)

Python CDP client using Scapy and Pyinstaller

I am trying to write a Python-based CDP client, similar to WinCDP for those familiar. For the purposes of troubleshooting compilation I have a significantly shortened version:
# Suppress Scapy IPv6 warning
import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
import re from scapy.all import *
load_contrib("cdp") class main:
def __init__(self):
self.filter = "ether host 01:00:0c:cc:cc:cc"
self.interfaces = str(ifaces)
print(self.interfaces)
try:
self.p = sniff(count=1,iface='Intel(R) 82578DM Gigabit Network Connection',filter=self.filter,timeout=60)
except:
print('OUCH! Something went wrong.')
else:
print('Finished processing...')
print("DeviceID: {}".format(self.p[0].payload["CDPMsgDeviceID"].val.decode('utf-8')))
print("PortID: {}".format(self.p[0].payload["CDPMsgPortID"].iface.decode('utf-8')))
print("NativeVLAN: {}".format(self.p[0].payload["CDPMsgNativeVLAN"].vlan))
print("IPv4addr: {}".format(self.p[0].payload["CDPAddrRecordIPv4"].addr))
print("Model: {}".format(self.p[0].payload["CDPMsgPlatform"].val.decode('utf-8')))
print("Duplex: {}".format(self.p[0].payload["CDPMsgDuplex"].duplex))
print("VTP Domain: {}".format(self.p[0].payload["CDPMsgVTPMgmtDomain"].val.decode('utf-8')))
if __name__ == "__main__": main()
On all versions of Python I've tried this produces results similar to the following:
INDEX IFACE IP MAC
10 Hyper-V Virtual Ethernet Adapter 172.31.253.241 78:15:27:01:22:F1
11 Intel(R) 82578DM Gigabit Network Connection 10.X.Y.Z 78:2B:CB:00:11:22
21 Hyper-V Virtual Ethernet Adapter #2 10.0.75.1 00:15:5D:CD:BE:03
26 Npcap Loopback Adapter 127.0.0.1 00:00:00:00:00:00
4 VirtualBox Host-Only Ethernet Adapter #2 192.168.56.1 0A:00:27:00:00:04
9 NETGEAR WNA3100M N300 Wireless Mini USB Adapter 2C:B0:5D:00:11:22
Finished processing...
DeviceID: switch01
PortID: GigabitEthernet5/0/29
NativeVLAN: 120
IPv4addr: 10.X.Y.Z
Model: cisco WS-C2960X-48FPD-L
Duplex: 1
VTP Domain: XYZ
I have managed to get the script to compile and it will run with the following:
pyinstaller -F cdpscript.py --hidden-import=queue
But, when the executable is run the output is:
INDEX IFACE IP MAC
OUCH! Something went wrong.
Which leads me to believe that enough of Scapy is running to print the headers of the ifaces command, but nothing else works. This was done on Python 3.6.6 as the Pyinstaller documentation indicates this is the most recent version supported, with Scapy 2.4.0 and PyInstaller 3.3.1.
I'm hoping to be able to give my techs an executable on a USB drive they can run and get CDP information without having to install anything locally, similarly to how we had been using WinCDP. Except, WinCDP has not been playing well with Windows 10 lately. I am hoping to create our own version so we can do fancier stuff like stick information in a database to track our machines. At any rate, none of this fun can happen if I can't get the script to compile into a working exe. Also, does anyone familiar with Scapy know if NPcap is going to have to be installed on the target machines? Any help would be greatly appreciated.

how can i connect and send commands to a serial port while another program is using it?

I am using a telit he910g card. it is connected to my PC directly using a miniPCI slot.
I am using it for 3G internet connection and A-GPS/GPS services.
My system is running linux mint 17.1, the 3G connection is handled using the network manager APP and works great. The 3G connection is started and handled using a module that is part of a program I am writing.
The code I am using in order to connect to the serial port is this:
def _connect_to_device(self):
""" Connect to a serial port """
try:
self._device = serial.Serial(self._filename, baudrate=self._baud_rate)
except StandardError, e:
raise StandardError("Couldn't connect to GPS device. Error: %s" % str(e))
When I use the python program alone it works great. But when I try and use it while the 3G is on i cant connect to the serial device. The wierd thing is that if I try to connect to it using a program like "minicom" while 3G is turned on it DOES work.
So my question is: how can I make both run and work together? since now they are mutually exclusive.
thanks to all who help. :)
Glad you found a way round your problem. Just for completeness:
Normally, serial ports can be opened by multiple processes.
If one of them does ioctl(,TIOCEXCL) on the open file then further opens will return EBUSY until everyone closes the device. Only root can get past this and open the device at all times.
If root opens the device and does an ioctl(,TIOCNXCL), then other processes can open the device too.
In python, TIOCNXCL isnt defined anywhere, but you can do the ioctl (eg on stdin) with:
import fcntl
TIOCEXCL = 0x540c # from /usr/lib64/perl5/asm-generic/ioctls.ph
TIOCNXCL = 0x540d
print fcntl.ioctl(0, TIOCNXCL)
Ok, so it is solved.
the issue was that the telit module has 2 ports /dev/ttyACM0 (high speed) and /dev/ttyACM3 (lower speed).
I tried to connect to the high speed one, but apparently the 3G uses that one and it causes contentions.
So moving to use the lower speed port in my script solved the issue.

WakeUp On Lan with Python

I am writing as application to Switch On Systems on Network using WakeOnLan feature.
I googled and able to get the code from here. My code looks like below.
I have forwarded port 9 in my router also.
I have Enabled Wake On Lan Options for the network Card from Power Management. I followed instructions from here
I have installed Wake on Lan Monitor/Sniffer from here to check if i am able to receive magic Packet to wakeup. And the system is receiving magic packets. When i shutdown and run WOL python script from another system (Laptop) on same network, My system doesn't power on.
Can anyone suggest me solution.
My systems are
Desktop with Win 8.1 which need to be wake On Lan.
Laptop with Win 8 which need to run application and send magic packet to desktop.
My LAN IPs range from 172.16.0.1 and so on, so used 172.16.255.255 as broadcast address.
import sys, struct, socket
# Configuration variables
broadcast = ['172.16.255.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',
'mars' : '00:10:DC:34:B2:87',
}
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
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(*macs):
if len(macs) == 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 macs:
if i[0] != '/':
if ":" in i:
# Wake up using MAC address
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(macs) == 2:
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('My System MAC address')
You need to check whether the system reacts to getting the WOL-packets, not only that it's able to receive it (i.e. actually wakes up). If not you need to turn that on either trough special software or in the BIOS-settings of your computer.
I also have the experience that on most laptops you need to have the power plugged in, and also have the ethernet cable having been plugged in the computer before you turn it off to work properly.
To test if it works on your computer, download an existing software for sending WOL Magic Packets and make sure that works before you make an assumption that it's something wrong in your code.
In Linux (debian based example) all you need to do is:
sudo apt-get install etherwake
and then do
wakeonlan MAC-ADDRESS
I know this thread is old, but did you manage to make it work?
First of all, I see you were using Win8.1
According to wikipedia:
"The ability to wake from a hybrid shutdown state (S4) or a fully
powered off state (S5) is unsupported in Windows 8 and above,[20][21]
and Windows Server 2012 and above.[22] This is because of a change in
the OS behavior which causes network adapters to be explicitly not
armed for WOL when shutdown to these states occurs. WOL from a sleep
state (S3) or non-hybrid hibernation state (S4) is supported."
So I'd suggest to try with a different machine/OS, and make sure the WoL option is enabled in the BIOS.
Edit: I've just made a small python app and it works wether I use the '!' operator or not. Therefore, I'm not sure about the following lines:
Also, I see you were using the default byte order in your pack:
struct.pack('BBBBBB',
Aren't you supposed to use the '>' or '!' (big-endian / network) operator?
e.g.
struct.pack('!BBBBBB',
I'm afraid if you don't use the big-endian operator, it will default to your system way of encoding, and on Intel machines it will be the little-endian encoding scheme.
So you're sending your bytes in the wrong order.
https://docs.python.org/3.0/library/struct.html
https://en.wikipedia.org/wiki/Endianness
I use wireshark to trace my WOL packet
I tested my code and it works.
for the wol in windows 8 + you have to uncheck the fast booting
(like i said before)
if you want to acces the remote pc for shutting down or check logged in status
or to logon
you need to add something into the regestry off the remote pc
see this picture to see where to add in regestry
(also) like i said before :)
if you don't do that, you cannot have remote acces (acces denied (5))
you can check it with cmd send a shutdown -s -m \ipadressOfTheRemotePC
i just created some massive software to wake up the other pc
check logged in or not and if its not it will do it for you if 1 of both are logged in.
The code i used for my wol packet is :
see this picture of my code

Simple file transfer over wifi between computer and mobile phone using python

I'd like to be able to transfer files between my mobile phone and computer. The phone is a smartphone that can run python 2.5.4 and the computer is running windows xp (with python 2.5.4 and 3.1.1).
I'd like to have a simple python program on the phone that can send files to the computer and get files from the computer. The phone end should only run when invoked, the computer end can be a server, although preferably something that does not use a lot of resources. The phone end should be able to figure out what's in the relevant directory on the computer.
At the moment I'm getting files from computer to phone by running windows web server on the computer (ugh) and a script with socket.set_ default _ access_point (so the program can pick my router's ssid or other transport) and urlretrieve (to get the files) on the phone. I'm sending files the other way by email using smtplib.
Suggestions would be appreciated, whether a general idea, existing programs or anything in between.
I would use paramiko. It's secure fast and really simple. How bout this?
So we start by importing the module, and specifying the log file:
import paramiko
paramiko.util.log_to_file('/tmp/paramiko.log')
We open an SSH transport:
host = "example.com"
port = 22
transport = paramiko.Transport((host, port))
Next we want to authenticate. We can do this with a password:
password = "example101"
username = "warrior"
transport.connect(username = username, password = password)
Another way is to use an SSH key:
import os
privatekeyfile = os.path.expanduser('~/.ssh/id_rsa')
mykey = paramiko.RSAKey.from_private_key_file(privatekeyfile)
username = 'warrior'
transport.connect(username = username, pkey = mykey)
Now we can start the SFTP client:
sftp = paramiko.SFTPClient.from_transport(transport)
Now lets pull a file across from the remote to the local system:
filepath = '/home/zeth/lenna.jpg'
localpath = '/home/zeth/lenna.jpg'
sftp.get(filepath, localpath)
Now lets go the other way:
filepath = '/home/zeth/lenna.jpg'
localpath = '/home/zeth/lenna.jpg'
sftp.put(filepath, localpath)
Lastly, we need to close the SFTP connection and the transport:
sftp.close()
transport.close()
How's that?? I have to give credit to this for the example.
I ended up using python's ftplib on the phone and FileZilla, an ftp sever, on the computer. Advantages are high degree of simplicity, although there may be security issues.
In case anyone cares, here's the guts of the client side code to send and receive files. Actual implementation has a bit more infrastructure.
from ftplib import FTP
import os
ftp = FTP()
ftp.connect(server, port)
ftp.login(user, pwd)
files = ftp.nlst() # get a list of files on the server
# decide which file we want
fn = 'test.py' # filename on server and for local storage
d = 'c:/temp/' # local directory to store file
path = os.path.join(d,fn)
r = ftp.retrbinary('RETR %s' % fn, open(path, 'wb').write)
print(r) # should be: 226 Transfer OK
f = open(path, 'rb') # send file at path
r = ftp.storbinary('STOR %s' % fn, f) # call it fn on server
print(r) # should be: 226 Transfer OK
f.close()
ftp.quit()
There are a couple of examples out there, but you have to keep in mind that, IIRC, PyBluez will work only on Linux.
I've previously done OBEX-related things, mostly fetching things from
mobile phones, using the obexftp program 2 which is part of the
OpenOBEX project 3. Naturally, you can call the obexftp program from
Python and interpret the responses and exit codes using functions in
the os, popen2 and subprocess modules. I believe that obexftp also
supports "push" mode, but you could probably find something else
related to OpenOBEX if it does not.
Since Bluetooth communications are supported using sockets in GNU/
Linux distributions and in Python (provided that the Bluetooth support
is detected and configured), you could communicate with phones using
plain network programming, but this would probably require you to
implement the OBEX protocols yourself - not a straightforward task for
a number of reasons, including one I mention below. Thus, it's
probably easier to go with obexftp at least initially.
You also have lightblue, that is a cross-os bluetooth library.
There is also a complete script, PUTools: Python Utility Tools for PyS60 Python (examples has Windows screenshots), that has a:
Python interpreter that takes input and shows output on PC, connects over Bluetooth to phone, and executes on the phone. You also get simple shell functionality for the phone (cd, ls, rm, etc.). The tool also allows you to synchronize files both from PC to phone (very useful in application development) and from phone to PC (your images, logfiles from the program you are working on, etc.).

Categories

Resources