How do you get correct MAC/Ethernet id of local network card using python?
Most of the article on Google/stackoverflow suggests to parse the result of ipconfig /all (windows) and ifconfig (Linux).
On windows (2x/xp/7) 'ipconfig /all' works fine but is this a fail safe method?
I am new to linux and I have no idea whether 'ifconfig' is the standard method to get MAC/Ethernet id.
I have to implement a license check method in a python application which is based on local MAC/Ethernet id.
There is a special case when you have a VPN or virtualization apps such as VirtualBox installed. In this case you'll get more then one MAC/Ethernet Ids. This is not going to be a problem if I have to use parsing method but I am not sure.
Cheers
Prashant
import sys
import os
def getMacAddress():
if sys.platform == 'win32':
for line in os.popen("ipconfig /all"):
if line.lstrip().startswith('Physical Address'):
mac = line.split(':')[1].strip().replace('-',':')
break
else:
for line in os.popen("/sbin/ifconfig"):
if line.find('Ether') > -1:
mac = line.split()[4]
break
return mac
Is a cross platform function that will return the answer for you.
On linux, you can access hardware information through sysfs.
>>> ifname = 'eth0'
>>> print open('/sys/class/net/%s/address' % ifname).read()
78:e7:g1:84:b5:ed
This way you avoid the complications of shelling out to ifconfig, and parsing the output.
I have used a socket based solution, works well on linux and I believe windows would be fine too
def getHwAddr(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
info = fcntl.ioctl(s.fileno(), 0x8927, struct.pack('256s', ifname[:15]))
return ''.join(['%02x:' % ord(char) for char in info[18:24]])[:-1]
getHwAddr("eth0")
Original Source
Related
I am trying to print to a TM-T20II thermal printer so I can print receipts. Here is my code:
from escpos import printer
from escpos import *
import escpos
from escpos import config
import usb.core
import usb.util
import usb.backend.libusb1
from ctypes import c_void_p, c_int
backend = usb.backend.libusb1.get_backend(find_library=lambda x: "libusb-1.0.dll")
backend.lib.libusb_set_option.argtypes = [c_void_p, c_int]
backend.lib.libusb_set_option(backend.ctx, 1)
p = printer.Usb(0x04b8,0x0e15,0,0x82,0x01, backend=backend)
p.text('test')
I am using a usbdk backend, without it I get a 'NotImplementedError: Operation not supported or unimplemented on this platform.' I'm doing this because for my program to work I need to use the default Epson drivers. When I run this code the error I get is:
<File "C:\Users\maxsl\anaconda3\lib\site-packages\usb\core.py", line
234, in get_interface_and_endpoint
return self._ep_info[endpoint_address]
KeyError: 1
During handling of the above exception, another exception occurred:
File
"C:\Users\maxsl\anaconda3\lib\site-packages\usb\backend\libusb1.py",
line 604, in _check
raise USBError(_strerror(ret), ret, _libusb_errno[ret])
USBError: [Errno None] Other error>
This error only occurs when I add p.text() in. Finding the printer and everything else is no problem. I also want to say that write() works in the PyUSB module, but it would be much more convenient for me to not have to translate the outputs in my program to the confusing ESC/P language.
I am using Spyder 4 with anaconda (python 3.7) 64-bit, libusb 1.0.22b9, most recent pyusb on github (PyPi version got unimplemented error), and python-escpos 3.0a8. I believe they are all 64-bit as well. I have the libusb1.dll from 64x folder in my System32 and the 86x one in SysWoW64 as recommended. I also have Usbdk installed. Please let me know if you have any ideas to fix or if you need more details. Been googling this for like a week.
Isn't it a problem with the printer's USB mode setting?
TM-T20II printer has the modes of USB vender-defined class (COM Port) and USB printer class.
The VID/PID is USB vender-defined class=0x04b8:0x0202 and USB printer class=0x04b8:0x0e15 respectively.
TM-T20II Technical Reference Guide page 89
You should be able to change it with the printer's setting utility.
Alternatively, try changing the PID designation to 0x0202 as is, or try communicating as a COM port instead of a raw USB device.
Or it is possible that the advanced printer driver or Windows print spooler is already using the device and other programs cannot be used.
If the device driver is installed, try uninstalling it.
For anyone else with the same problem as me, what I did was I installed Epson's TM Virtual Port Driver and set the printer to a COM port. I then had to go into the printer's settings and manually change the port to the virtual one. I then altered my code to this:
from escpos import printer
pr = printer.Serial('COM2')
data= '''
hello world
'''
pr.text(data)
pr.close()
And it finally worked! You can see I cut my code down quite a bit. It turns out I don't even need to change the backend. So strange Usb doesn't work but serial does. As long as it works though! Thanks to kunif for the guidance to my solution, never even considered checking the serial ports.
I am trying to learn how to send a list of lists in Python to R -script which runs statistical methods and gives two or three data frames back to Python
I stumbled across the pyRserve package. I was able to follow the manual in their documentation and everything works great in command line (>>> ). When I run a script, it does not stop. I have installed Rserve package and started its service in RStudio. Below is the code:
import pyRserve
print "here1" #prints this line...
conn = pyRserve.connect(host='localhost', port=6311)
print "here2"
a= conn.eval('3+5')
print a
Can anyone please help?
The (docs) suggest:
$ python
>>> import pyRserve
>>> conn = pyRserve.connect()
And then go on with:
To connect to a different location host and port can be specified explicitly:
pyRserve.connect(host='localhost', port=6311)
This is not meant to indicate that both lines should be run. The second line should be viewed as a potential modifier for the first. So if you need an alternate address or port, then it should look like:
$ python
>>> import pyRserve
>>> conn = pyRserve.connect(host='localhost', port=6311)
Also note this caveat for windows users:
Note On some windows versions it might be necessary to always provide ‘localhost’ for connecting to a locally running Rserve instance.
I am looking for a Python solution for obtaining the current machine default domain name, one that will work on Linux, Mac OS X and Windows.
So far I discovered that:
Linux has dnsdomainname which returns it
Try:
#!/usr/bin/env python
import socket
def get_dns_domain():
return socket.getfqdn().split('.', 1)[1]
print (get_dns_domain()) # to match python>2.7
Try:
from socket import gethostname
machine_name=gethostname()
print(machine_name)
I am reading a Python book and in it there is a script to use scapy, the Python tool/module, to scan a subnet for any hosts that are up and report back their IP and MAC addresses. This script is an enhancement on a previous one that was calling /usr/bin/arping. That previous script only allowed one IP address at a time and was platform dependent on the arping tool being available. Apparently, this script (that does not work for me) is platform independent!
If someone could look over the script and debug it that would be awesome. Here is the script:
#! /usr/bin/env python
from scapy.all import srp
from scapy.all import Ether, ARP, conf
import sys
def arping(iprange="10.0.1.0/24"):
"""Arping function takes IP Address or Network, returns nested mac/ip list"""
#conf, verb = 0
ans, unans = srp(Ether(dst="ff:ff:ff:ff:ff:ff")/ARP(pdst=iprange), timeout=2)
collection = []
for snd, rcv in ans:
result = rcv.sprintf(r"%ARP.psrc% %Ether.src%").split()
collection.append(result)
return collection
if __name__ == "__main__":
if len(sys.argv) > 1:
for ip in sys.argv[1:]:
print "arping", ip
print arping(ip)
else:
print arping()
The script does not work. It just prints that it is scanning stuff but that nothing was found.
I looked on this website and found a tutorial that also did not work. That website with the relevant content is here: http://www.secdev.org/projects/scapy/doc/usage.html#arp-ping
Please, see below for a sample of the output I obtain when running this script:
loser#loser:~/Desktop/pyFun2$ gedit arp_scanz.py
loser#loser:~/Desktop/pyFun2$ sudo python arp_scanz.py
WARNING: No route found for IPv6 destination :: (no default route?)
Begin emission:
Finished to send 256 packets.
Received 0 packets, got 0 answers, remaining 256 packets
[]
Does anyone out there know what I am missing?
UPDATE - SOLUTION
change the srp function or method call to specify the exact interface to scan on like so:
ans, unans = srp(Ether(dst="ff:ff:ff:ff:ff:ff")/ARP(pdst=iprange),iface="en1", timeout=2)
Could be any number of things. I seem to have the script running just fine on my network using valid IP starting points.
Are you putting in a proper IP range?
For example I use:
def arping(iprange="192.168.1.*"):
which produces the correct results and identical results to scapy's built in arping() function.
So I think perhaps it's not the code exactly but the range you are attempting.
A client of mine hosed part of their registry. For some reason, a bunch of sub keys under the HKEY_CLASSES_ROOT have no permissions set. So I am going through the keys and manually setting keys as such:
Add Administrators as a group
Set Administrators as the Owner
There are potentially thousands of these that need to be set and it's a 10-12 step process to do for each key. So I want to automate the process via Python. Is there a module that can accomplish both of these?
Thanks!
After almost a whole day research my solution to working with windows registry and permissions is to use SetACL. You could use a COM object, or use the binary file and the subprocess module.
Here is a snippet from what I used in my code to modify the permissions in a mixed environment (I have ~50 Windows machines with 32bit and 64bit, with Windows 7 and Windows XP pro ...):
from subprocess import Popen, PIPE
def Is64Windows():
'''check if win64 bit'''
return 'PROGRAMFILES(X86)' in os.environ
def ModifyPermissions():
"""do the actual key permission change using SetACL"""
permissionCommand = r'SetACL.exe -on "HKLM\Software\MPICH\SMPD"'\
+' -ot reg -actn ace -ace "n:Users;p:full"'
permissionsOut = Popen(permissionCommand, stdout = PIPE, stderr = PIPE)
pout, perr = permissionsOut.communicate()
if pout:
print pout
sys.exit(0)
elif perr:
print perr
sys.exit(1)
def main():
... some code snipped ...
os.chdir('SetACL')
if Is64Windows():
os.chdir('x64')
ModifyPermissions()
else:
os.chdir('x86')
ModifyPermissions()
So, it's not really pure Python, but it works.