Problems with pyUSB - python

I have been trying to make a program with Python which sends commands to a DYMO labelmanager PnP usb device. I tried installing pyUSB and tried the code provided in pyUSB tutorial to figure out a bit how the USB communicating works, but it doesn't work. Code from pyUSB tutorial:
(I have changed the idVendor and idProduct to cope with my device. It finds the device but writing fails)
import usb.core
import usb.util
# find our device
dev = usb.core.find(idVendor=0x0922, idProduct=0x1001)
# was it found?
if dev is None:
raise ValueError('Device not found')
# set the active configuration. With no arguments, the first
# configuration will be the active one
dev.set_configuration()
# get an endpoint instance
cfg = dev.get_active_configuration()
interface_number = cfg[(0,0)].bInterfaceNumber
alternate_setting = usb.control.get_interface(interface_number)
intf = usb.util.find_descriptor(
cfg, bInterfaceNumber = interface_number,
bAlternateSetting = alternate_setting
)
ep = usb.util.find_descriptor(
intf,
# match the first OUT endpoint
custom_match = \
lambda e: \
usb.util.endpoint_direction(e.bEndpointAddress) == \
usb.util.ENDPOINT_OUT
)
assert ep is not None
# write the data
ep.write('test')
and it gives an error:
Traceback (most recent call last):
File "C:\Python27\proc\labelprinttest.py", line 18, in <module>
alternate_setting = usb.control.get_interface(interface_number)
TypeError: get_interface() takes exactly 2 arguments (1 given)
where is the problem?
(well of course there reads that the function takes 2 arguments and only 1 is given, but I have tried to investigate and I have no idea what the other needed argument is)

The definition of get_interface() is as follows:
def get_interface(dev, bInterfaceNumber):
r"""Get the current alternate setting of the interface.
dev is the Device object to which the request will be
sent to.
"""
So, try to call it using usb.control.get_interface(dev, interface_number)

Related

Python : PyUSB can't access usb device

I am trying to read an usb bar code reader from my python script, via the https://github.com/pyusb/pyusb library.
import usb.core
import usb.util
VENDOR_ID = 8208
PRODUCT_ID = 30264
dev = usb.core.find(idVendor=VENDOR_ID,
idProduct=PRODUCT_ID)
dev.set_configuration()
cfg = dev.get_active_configuration()
intf = cfg[(0,0)]
ep = usb.util.find_descriptor(
intf,
# match the first OUT endpoint
custom_match = \
lambda e: \
usb.util.endpoint_direction(e.bEndpointAddress) == \
usb.util.ENDPOINT_IN)
data = ep.read(ep.wMaxPacketSize, 8000000)
Unfortunately, this leads to a "USBError: [Errno 13] Access denied (insufficient permissions)" issue.
I tried to run the script as a sudo, but it didn't help. The script work fine on my Ubuntu laptop, but I am now trying to move it to Mac OS. One of the differences is that I do have a "detach_kernel" before hand on Linux, but this function make a fail with "not implemented on this OS" error with Mac Os...

ZeroMQ threw ZMQError on socket bind to an ipc:// protocol address (python)

I'm trying to use the IPC protocol with ZeroMQ in Python.
import sys
import time
from random import randint
import zmq
def main(url=None):
ctx = zmq.Context.instance()
publisher = ctx.socket(zmq.PUB)
if url:
publisher.bind(url)
else:
publisher.bind('ipc://var/run/fast-service')
# Ensure subscriber connection has time to complete
time.sleep(1)
# Send out all 1,000 topic messages
for topic_nbr in range(1000):
publisher.send_multipart([
b"%03d" % topic_nbr,
b"Save Roger",
])
if __name__ == '__main__':
main(sys.argv[1] if len(sys.argv) > 1 else None)
It gives the following error:
Traceback (most recent call last):
File "pathopub.py", line 43, in <module>
main(sys.argv[1] if len(sys.argv) > 1 else None)
File "pathopub.py", line 19, in main
publisher.bind("ipc://var/run/fast-service")
File "zmq/backend/cython/socket.pyx", line 547, in zmq.backend.cython.socket.Socket.bind
zmq.error.ZMQError: No such file or directory for ipc path "var/run/fast-service".
I don't understand why would this happen with the socket.bind() function, since in the documentation it says:
When binding a socket to a local address using zmq_bind() with the ipc transport, the endpoint shall be interpreted as an arbitrary string identifying the pathname to create.
which means that it is not necessary to supply an already created directory.
The URL scheme is ipc://. You need to add an absolute path /var/run/fast-service. So,
publisher.bind('ipc:///var/run/fast-service')
More generally the URL is ipc://<host>/<path>. You want local host, so that part is empty. A file system URL is similar, file:///home/foo/bar.txt references /home/foo/bar.txt on the local host.

GUID number of windows interface giving error: ValueError: Unknown network interface '{1619EEF1-4D71-4831-87AC-8E5DC3AA516A}'

Import scapy version 2.4.0. I am only using version 2.4.0 for my project
import scapy.all as scapy
import sys
by using IP address this function return related MAC address of the target
def get_mac(ip):
arp_request = scapy.ARP(pdst=ip)
broadcast = scapy.Ether(dst="ff:ff:ff:ff:ff:ff")
arp_request_broadcast = broadcast/arp_request
answered_list = scapy.srp(arp_request_broadcast, timeout=1, verbose=False)[0]
return answered_list[0][1].hwsrc
def sniff(interface):
scapy.sniff(iface=interface, store=False, prn=process_sniffed_packet)
This function checks whether default gateway MAC address is equal to my PC's MAC address table. if not it says "[+] You are under attack!!
def process_sniffed_packet(packet):
if packet.haslayer(scapy.ARP) and packet[scapy.ARP].op == 2:
count = 1
try:
real_mac = get_mac(packet[scapy.ARP].psrc)
response_mac = packet[scapy.ARP].hwsrc
if real_mac != response_mac:
count = count+1
print(str(count) + "[+] You are under attack!!")
sys.stdout.flush()
except IndexError:
pass
in Linux, we can use a value like 'etho' but In windows, I have to use GUID value to get the result. I am running this code in Windows Machine.
sniff('{1619EEF1-4D71-4831-87AC-8E5DC3AA516A}')
But this code return error
This is the Error that got raised
raise ValueError("Unknown network interface %r" % name)
ValueError: Unknown network interface '{1619EEF1-4D71-4831-87AC-
8E5DC3AA516A}'
On Windows, you need to provide a complete interface name / object, to be able to sniff on it.
First, have a look at what is available using IFACES.show() in a Scapy shell.
Then to get the interface, you can either use:
iface = IFACES.dev_from_name("...") (or dev_from_pcapname, dev_from_id... have a look at help(IFACES) to see what’s available)
iface = "the full name as printed above"
Then use it via sniff(iface=iface).
You could provide the pcap_name, but not the GUID: for instance, it would be something like \\Device\\NPF_{...} rather than just {...}.
Also, please use scapy 2.4.3rc1 (or at least 2.4.2) to be sure you’re up-to-date
I solved the scapy error ValueError: Unknown network interface on windows by installing npcap

No module named usb.core

How can I remove this error in the below mentioned program? The error iI'm getting is
ImportError: No module named usb.core
and my code is:
import usb.core
import usb.util
# find our device
dev = usb.core.find(idVendor=0xfffe, idProduct=0x0001)
# was it found?
if dev is None:
raise ValueError('Device not found')
# set the active configuration. With no arguments, the first
# configuration will be the active one
dev.set_configuration()
# get an endpoint instance
cfg = dev.get_active_configuration()
intf = cfg[(0,0)]
ep = usb.util.find_descriptor(
intf,
# match the first OUT endpoint
custom_match = \
lambda e: \
usb.util.endpoint_direction(e.bEndpointAddress) == \
usb.util.ENDPOINT_OUT)
assert ep is not None
# write the data
ep.write('test')
OS is windows 8 64-bit [...]
ValueError: No backend available
Allow me to translate: You forgot to install the correct USB driver.
USB devices need a driver to work in Windows. Look at PyUSB website for details, and use Zadig to generate and install the driver (e.g. LibUSB-Win32) for you. This program takes care of the certificate that Windows 8 wants to see for your drivers inf file.
Btw: The VID you should use for USB development is 0x4242.
For error:
C:\Users\RAHUL\Desktop\python progrms\USBsample.py, line 5, in <module>
dev = usb.core.find(idVendor=0xfffe, idProduct=0x0001) File "C:\Python27\lib\site-
packages\usb\core.py", line 864, in find raise ValueError('No backend available')
ValueError: No backend available
Download and install libusb-win32-devel-filter-1.2.6.0.exe. It should work.
python -m pip install pyusb libusb
Fixed this for me.

Communication with the USB device in Python

I want to communicate with and send data to a USB device. I am able to find the device but while attaching the device with the kernel driver it is giving USB Error: Resource Busy. The following is my code:
import usb
dev = usb.core.find(idVendor=0x0403, idProduct=0x6001)
dev.set_configuration()
cfg = dev.get_active_configuration()
dev.attach_kernel_driver(interface)
interface_number = cfg[(0, 0)].bInterfaceNumber
alternate_settting = usb.control.get_interface(interface_number)
intf = usb.util.find_descriptor(
cfg, bInterfaceNumber=interface_number,
bAlternateSetting=alternate_setting)
ep = usb.util.find_descriptor(
intf, custom_match=lambda e:
usb.util.endpoint_direction(e.bEndpointAddress) == usb.util.ENDPOINT_OUT)
dev.detach_kernel_driver(interface)
ep.write("\r" + linea1[:19] + "\n\r" + " " * (20 - len(linea2)) + linea2)
Assuming your using Linux and libusb-1.0 as a PyUSB's backend library.
According to the libusb documentation:
// Detach a kernel driver from an interface.
// If successful, you will then be able to claim the interface and perform I/O.
int libusb_detach_kernel_driver (libusb_device_handle *dev,
int interface_number)
// Re-attach an interface's kernel driver, which was previously
// detached using libusb_detach_kernel_driver().
int libusb_attach_kernel_driver(libusb_device_handle *dev,
int interface_number)
So basically, you need to call detach_kernel_driver first to detach already attached kernel driver (if any) from the device's interface, so you can communicate with it in your code (it's either your code or some kernel driver talking to the device's interface). When you're done, you may want to call attach_kernel_driver to re-attach the kernel driver again.
I believe there's no need to call any of those C functions/Python methods if you can ensure that no kernel driver is loaded for a given device (or manually unload it before running your code).
Edit:
I just got this piece of code (based on your sample) working. Note: for simplicity I've hardcoded 0 as interface number for detach_kernel_driver and attach_kernel_driver - you should make it smarter, I suppose.
import usb
dev = usb.core.find(idVendor=0x0403, idProduct=0x6001)
reattach = False
if dev.is_kernel_driver_active(0):
reattach = True
dev.detach_kernel_driver(0)
dev.set_configuration()
cfg = dev.get_active_configuration()
interface_number = cfg[(0,0)].bInterfaceNumber
alternate_settting = usb.control.get_interface(dev, interface_number)
intf = usb.util.find_descriptor(cfg, bInterfaceNumber = interface_number,
bAlternateSetting = alternate_settting)
ep = usb.util.find_descriptor(intf,custom_match = \
lambda e: \
usb.util.endpoint_direction(e.bEndpointAddress) == \
usb.util.ENDPOINT_OUT)
ep.write("test\n\r")
# This is needed to release interface, otherwise attach_kernel_driver fails
# due to "Resource busy"
usb.util.dispose_resources(dev)
# It may raise USBError if there's e.g. no kernel driver loaded at all
if reattach:
dev.attach_kernel_driver(0)

Categories