No module named usb.core - python

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.

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...

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

Executable out of script containing serial_for_url

I have developed a python script for making a serial communication to a digital pump. I now need to make an executable out of it. However even though it works perfectly well when running it with python and py2exe does produce the .exe properly when I run the executable the following error occurs:
File: pump_model.pyc in line 96 in connect_new
File: serial\__init__.pyc in line 71 in serial_for_url
ValueError: invalid URL protocol 'loop' not known
The relevant piece of my code is the following:
# New serial connection
def connect_new(self, port_name):
"""Function for configuring a new serial connection."""
try:
self.ser = serial.Serial(port = port_name,\
baudrate = 9600,\
parity = 'N',\
stopbits = 1,\
bytesize = 8,\
timeout = self.timeout_time)
except serial.SerialException:
self.ser = serial.serial_for_url('loop://',\
timeout = self.timeout_time) # This line BLOWS!
except:
print sys.exc_info()[0]
finally:
self.initialize_pump()
I should note that the application was written in OSX and was tested on Windows with the Canopy Python Distribution.
I had the exact same problem with "socket://" rather than "loop://"
I wasn't able to get the accepted answer to work however the following seems to succeed:
1) Add an explicit import of the offending urlhandler.* module
import serial
# explicit import for py2exe - to fix "socket://" url issue
import serial.urlhandler.protocol_socket
# explicit import for py2exe - to fix "loop://" url issue (OP's particular prob)
import serial.urlhandler.protocol_loop
# use serial_for_url in normal manner
self._serial = serial.serial_for_url('socket://192.168.1.99:12000')
2) Generate a setup script for py2exe (see https://pypi.python.org/pypi/py2exe/) -- I've installed py2exe to a virtualenv:
path\to\env\Scripts\python.exe -m py2exe myscript.py -W mysetup.py
3) edit mysetup.py to include option
zipfile="library.zip" # default generated value is None
(see also http://www.py2exe.org/index.cgi/ListOfOptions)
3) build it:
path\to\env\Scripts\python.exe mysetup.py py2exe
4) run it
dist\myscript.exe
Found it!
It seems that for some reason the 'loop://' arguement can't be recognised after the .exe production.
I figured out by studying the pyserial/init.py script that when issuing the command serial.serial_for_url(‘loop://') you essentially call:
sys.modules['serial.urlhandler.protocol_loop’].Serial(“loop://“)
So you have to first import the serial.urlhandler.protocol_loop
and then issue that command in place of the one malfunctioning.
So you can now type:
__import__('serial.urlhandler.protocol_loop')
sys.modules[‘serial.urlhandler.protocol_loop’].Serial("loop://")
After this minor workaround it worked fine.

Problems with pyUSB

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)

all python windows service can not start{error 1053}

all python code service can install but cannot start
Error 1053: The service did not respond to the start or control request in a timely fashion".
since my service can install and start in my server.
i think my code has no problem.
but i still wonder is there a solution that i can solve this error in code
my service:
import win32serviceutil
import win32service
import win32event
import time
import traceback
import os
import ConfigParser
import time
import traceback
import os
import utils_func
from memcache_synchronizer import *
class MyService(win32serviceutil.ServiceFramework):
"""Windows Service."""
os.chdir(os.path.dirname(__file__))
conf_file_name = "memcache_sync_service.ini"
conf_parser = ConfigParser.SafeConfigParser()
conf_parser.read(conf_file_name)
_svc_name_, _svc_display_name_, _svc_description_ = utils_func.get_win_service(conf_parser)
def __init__(self, args):
if os.path.dirname(__file__):
os.chdir(os.path.dirname(__file__))
win32serviceutil.ServiceFramework.__init__(self, args)
# create an event that SvcDoRun can wait on and SvcStop can set.
self.stop_event = win32event.CreateEvent(None, 0, 0, None)
def SvcDoRun(self):
self.Run()
win32event.WaitForSingleObject(self.stop_event, win32event.INFINITE)
def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.stop_event)
LoggerInstance.log("memcache_sync service is stopped")
self.ReportServiceStatus(win32service.SERVICE_STOPPED)
sys.exit()
def Run(self):
try:
LoggerInstance.log("\n******\n\memcache_sync_service is running, configuration: %s\n******" % (self.conf_file_name,))
if ((not self.conf_parser.has_section('Memcache')) or
(not self.conf_parser.has_option('Memcache', 'check_interval'))):
LoggerInstance.log('memcache_sync_service : no Memcache service parameters')
self.SvcStop()
# set configuration parameters from ini configuration
self.check_interval = self.conf_parser.getint('Memcache', 'check_interval')
ms = MemcacheSynchronizer()
while 1:
ms.Sync()
time.sleep(self.check_interval)
except:
LoggerInstance.log("Unhandled Exception \n\t%s" % (traceback.format_exc(),))
if __name__ == '__main__':
win32serviceutil.HandleCommandLine(MyService)
execute result of "sc query [name]" cmd:
SERVICE_NAME: NewsMonitoringMemcacheSynchronizer
TYPE : 10 WIN32_OWN_PROCESS
STATE : 1 STOPPED
(NOT_STOPPABLE,NOT_PAUSABLE,IGNORES_SHUTDOWN)
WIN32_EXIT_CODE : 0 (0x0)
SERVICE_EXIT_CODE : 0 (0x0)
CHECKPOINT : 0x0
WAIT_HINT : 0x0
update:
i can run this service with debug mode, cmd:
memcache_syn_service.py debug
Had the same problem using pypiwin32 (version: 220) and python (version: 3.6). I had to copy :
"\Python36-32\Lib\site-packages\pypiwin32_system32\pywintypes36.dll"
to
"\Python36-32\Lib\site-packages\win32"
for the service to start (was working in debug mode)
If:
python your_service.py debug works, whilst
python your_service.py install + start it as a service fails with error 1053,
this command may help python C:\Python27\Scripts\pywin32_postinstall.py.
all my python coded windows service cannot run on my computer.
but all of them can start at our dev-server which means my code is correct.
but i found a alternative solution, run in debug mode:
any_service.py debug
Make sure you run the application with a different user than the default Local System user. Replace it with the user you successfully be able to run the debug command with.
To replace the user go to the windows services (start > services.msc)
Right click on the service you created > properties > Log On
Uncheck the Local System Account and enter your own.
All of the known fixes have failed me, and this one worked:
In services window:
right-click your installed service;
Go to Log On tab;
Select "This Account" and enter your user ID and pass;
Restart PC.
Has to do with Windows Permissions I was explained...
Method won't work if there's no password set for Windows User.
In my case the problem was from python37.dll not being at C:\Python37-x64\Lib\site-packages\win32.
Just copy it there and it will solve the problem
I had similar problem with a python service and found out that it was missing DLLs since the 'System Path' (not the user path) was not complete. Check the path in your dev-server and whether it matches the one at your computer (System path if service is installed as a LocalSystem service). For me I was missing python dlls' path c:\python27 (windows).
I had this issue and solved it two times in the same way, simply adding the Environment Variables.
I opened Environment Variables, and in system variable PATH added
C:\Users\MyUser\AppData\Local\Programs\Python\PythonXXX
C:\Users\MyUser\AppData\Local\Programs\Python\PythonXXX\Scripts
(Obviously change User name and XXX with Python version)

Categories