I'm trying to get the vendorId, the productCode and the SerialNumber of a usb device using python.
Therefore I created the following script which runs quite well in a linux environment.
import sys
import usb
devs = usb.core.find(find_all=True)
nCount=0
for dev in devs:
for cfg in dev:
intf = usb.util.find_descriptor(cfg,bInterfaceClass=0x8)
if intf is not None:
nCount += 1
try:
sys.stdout.write("USB device " + usb.util.get_string(dev,dev.iProduct,None) + '\n')
except:
sys.stdout.write("USB device " + str(nCount) + '\n')
sys.stdout.write("------" + '\n')
sys.stdout.write("VendorId = " + hex(dev.idVendor) + '\n')
sys.stdout.write("ProductId = " + hex(dev.idProduct) + '\n')
if not dev.iSerialNumber == 0:
try:
sys.stdout.write("SerialNbr = " + usb.util.get_string(dev,dev.iSerialNumber ) + '\n')
except NotImplementedError:
sys.stdout.write("Sreial-Number not readable")
else:
sys.stdout.write("SerialNbr = none" + '\n')
sys.stdout.write('\n')
As soon as a start the script in windows, the script returns an error "NotImplementedError" when calling the function usb.util.get_string(dev,dev.iSerialNumber)
I found that there is a problem with the windows drivers and the libusb.
The solution wI0m heading to, does not allow to change system drivers with Zadig first. IIt must be callable without changing drivers first.
So my question is, if it's possible to get the serial number with python on a windows system without changing the drivers first.
Related
I have writen a script in python to attempt to connect to a defined wifi network with a list of simple passwords.
import wifimangement_linux as wifi
import os
wifiname = input("Enter Wifi SSID: ")
print("Wifi not stored, testing password...")
file = open('/home/asive/Documents/seclists/wordlists/passwords.lst', 'r')
line = file.readlines()
for i in line:
try:
print("Testing Key " + i.strip())
stream = os.popen("iwconfig wlan0 essid " + wifiname() + " key s:" + i.strip())
except:
print (i.strip() + " failed, trying next.")
else:
print ("Success Key==" + i.strip())
The script only runs through the program seemingly without trying to connect.
i've tried using subprocess instead of os and running in root, including adding sudo to the bash command.
What am i doing wrong?
I'm trying to get a Python script to work that downloads a file and then loads the data into a mariadb. My best option seems to be using subprocess.run, as I cannot update the Python version to a version that includes the new mariadb connector.
I've tried different options:
subprocess.run(["mysql", "-u" + mdb_usr, "-p" + mdb_pwd, "database", " < " + file.sql])
subprocess.run(["mysql", "-u" + mdb_usr, "-p" + mdb_pwd, "database < " + file.sql])
subprocess.run(["mysql -u" + mdb_usr + " -p" + mdb_pwd + "database < " + file.sql], shell = True)
But none of them seems to work.
Without the < file.sql, I can get the script to work, but I can't seem to get the sql to execute. Can anyone point me in the right direction?
I am looking for a way to test whether code developed in Python 3.6 will be compatible with Python 2.7. Ideally - if not I would like to have the invalid syntax pointed out in some way. Thank you
Yes. Execute your code with python2.7 yourScript.py. If some modules need python3.*, you could write a second script only for python2.7? Hacky but it's the quick and lazy solution.
You should definitely check the version on startup. This snippet restartes the script automatically with the right version:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# pythonVersionCheck.py
import sys
import os
# Color codes for output
CRED = '\033[91m'
CGREEN = '\033[92m'
CEND = '\033[0m'
# Desired python version number
scriptVersion = "3.6"
# Check if script is executed with root. Get rid of this block if you don't need it
if os.geteuid() != 0:
print(CRED + "\nRestart the script with root privileges: 'sudo python"
+ scriptVersion + " " + sys.argv[0] + "'\n" + CEND)
sys.exit(0)
# Check if the script is running with the desired python version
if sys.version[:3] == scriptVersion:
print(CGREEN + "Script running with Python " + scriptVersion + CEND)
else:
print(CRED + "Script not running with Python " + scriptVersion + ". Restarting." + CEND)
try:
os.execv(sys.executable, ['python' + scriptVersion] + sys.argv)
except OSError as error:
print(CRED + "An error occured: " + str(error) + CEND)
# YOUR CODE HERE
Read up on portability between Python2.* and Python3.* here.
EDIT: As suggested by #MisterMiyagi, here some changes.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# pythonVersionCheck.py
import sys
import subprocess
import platform
# Desired python version number
scriptVersion = "2.7"
usedVersion = "{0}.{1}".format(sys.version_info.major,sys.version_info.minor)
opSys = platform.system()
# Check if the script is running with the desired python version
if usedVersion == scriptVersion:
print("Script running with Python " + scriptVersion)
else:
print("Script not running with Python " + scriptVersion + ". Restarting.")
if opSys == 'Linux' or opSys == 'Darwin':
subprocess.call('python' + scriptVersion + ' ' + sys.path[0] + '/' +
sys.argv[0], shell=True)
elif opSys is 'Windows':
print("py -" + scriptVersion + ' ' + sys.argv[0])
subprocess.call("py -" + scriptVersion + ' ' + sys.argv[0], shell=True)
else:
print("Can't detect os.")
# YOUR CODE HERE
It now uses subprocess instead of os.execv.
It now uses sys.version_info instead of sys.version.
It now checks what platform the user runs so now it is portable to Linux, Windows and Appletoshwin.
I am a little confused about the way Popen works and I am hoping this is something silly. I am never getting a completion, and poll seems to be returning something odd (log attached)
This is backing up a triplet of schemas (Tablespace) using a utility (CSSBACKUP) supplied to do this.
for i in range(len(schematype)):
schema_base = schemaname + '_' + schematype[i] # we need this without the trailing space.
outputstring = base_folder + '\\' + schemaname + '\\' + schema_base + '_' + timestr + '_cssbackup '
rc = os.unlink(outputstring) # wont run if there is a backup already
logstring = base_folder + '\\' + schemaname + '\\' + schema_base + '_' + timestr + '.log'
exString = "cssbackup " + phys_string + '-schema '+ schema_base + ' ' + '-file ' + outputstring + '-log '+ logstring
logging.debug(exString)
processlist.append(subprocess.Popen(exString)) # start a seperate thread for each one, but we don't want to proceed until processlist[].poll == None (thread is complete)
procdone[i] = False
Now that I have all the processes spawn, I need to sync them up
while finishit < len(schematype):
time.sleep(CSTU_CFG.get(hostname).get("logintv")) # need a delay to keep this program from thrashing
for i in range(len(schematype)): # check each of the procs
if procdone[i] is not True: # if it completed, skip it
if processlist[i].poll is not None: # if it returns something other than "none" it's still running
logging.debug(' Running '+ schematype[i] + ' ' + str(processlist[i])+ ' '+ str(time.time() - start_time))
procdone[i] = False
else:
procdone[i] = True # None was returned so it's finished
logging.debug(' Ended '+ schematype[i]) # log it
finishit = finishit + 1 # update the count
processlist[i].kill # kill the process that was running ( Saves memory )
logging.debug('Dump functions complete')
When I run this, I don't get what I am expecting. I was expecting a pid in the return but I dont see it. So what I get back isnt useful for the .poll command.
So the program runs forever even after the shell that it spawned are gone.
I'm missing something basic.
THanks
11:26:26,133 root, DEBUG Running local 30.014784812927246
11:26:26,133 root, DEBUG Running central 30.014784812927246
11:26:26,133 root, DEBUG Running mngt 30.014784812927246
11:26:56,148 root, DEBUG Running local 60.02956962585449
11:26:56,148 root, DEBUG Running central 60.02956962585449
11:26:56,148 root, DEBUG Running mngt 60.02956962585449
11:27:26,162 root, DEBUG Running local 90.04435467720032
11:27:26,162 root, DEBUG Running central 90.04435467720032
11:27:26,162 root, DEBUG Running mngt 90.04435467720032
11:27:56,177 root, DEBUG Running local 120.05913925170898
11:27:56,177 root, DEBUG Running central 120.05913925170898
11:27:56,177 root, DEBUG Running mngt 120.05913925170898
11:28:26,192 root, DEBUG Running local 150.07392406463623
You should call poll. if processlist[i].poll is not None will always evaluate to True, because processlist[i].poll is the function object, not the result of processlist[i].poll().
Edit:
This looks an quite complicated way to do something like
p = multiprocessing.Pool(n)
p.map_async(subprocess.call, commands)
As a suggestion, you may want to check the multiprocessing module.
I have an issue putting files to a server that contains hyphens ("-"), and I think that it may be because of how Linux is treating the file, but I am in no way sure. The script is scanning a folder for pictures/items, puts them in a list and then transferring all items to the server.
This is a part of the script:
def _transferContent(locale):
## Transferring images to server
now = datetime.datetime.now()
localImages = '/home/bcns/Pictures/upload/'
localList = os.listdir(localImages)
print("Found local items: ")
print(localList)
fname = "/tmp/backup_images_file_list"
f = open(fname, 'r')
remoteList = f.read()
remoteImageLocation = "/var/www/bcns-site/pics/photos/backup_" + locale + "-" + `now.year` + `now.month` + `now.day` + "/"
print("Server image location: " + remoteImageLocation)
## Checking local list against remote list (from the server)
for localItem in localList:
localItem_fullpath = localImages + localItem
if os.path.exists(localItem_fullpath):
if localItem in remoteList:
print("Already exists: " + localItem)
else:
put(localItem_fullpath, remoteImageLocation)
else:
print("File not found: " + localItem)
And this is the out put:
Directory created successfully
/tmp/bcns_deploy/backup_images_file_list
[<server>] download: /tmp/backup_images_file_list <- /tmp/bcns_deploy/backup_images_file_list
Warning: Local file /tmp/backup_images_file_list already exists and is being overwritten.
Found local items:
['darth-vader-mug.jpg', 'gun-dog-leash.jpg', 'think-safety-first-sign.jpg', 'hzmp.jpg', 'cy-happ-short-arms.gif', 'Hogwarts-Crest-Pumpkin.jpg']
Server image location: /var/www/bcns-site/pics/photos/backup_fujitsu-20131031/
[<server>] put: /home/bcns/Pictures/upload/darth-vader-mug.jpg -> /var/www/bcns-site/pics/photos/backup_fujitsu-20131031/
Fatal error: put() encountered an exception while uploading '/home/bcns/Pictures/upload/darth-vader-mug.jpg'
Underlying exception:
Failure
I have tried to remove the hyphons, and then the transfer works just fine.
Server runs Ubuntu 12.04 and client runs Debian 7.1 on ext3 disks.
Irritating error, but anyone out here that has a clue on what might make this error?
Dashes in command line options in Linux matter, but dashes in the middle of filenames are file.
Check file permissions -- it's possible that in transferring one file manually, the perms are set differently than if Fabric transfers.
I suggest using put() to transfer a directory at a time. This will help to make sure all the files (and permissions) are what they should be.
Example (untested):
def _transferContent(locale):
## Transferring images to server
now = datetime.datetime.now()
localImageDir = '/home/bcns/Pictures/upload/'
remoteImageDir = "/var/www/bcns-site/pics/photos/backup_" + locale + "-" + `now.year` + `now.month` + `now.day` + "/"
print("Server image location: " + remoteImageDir)
put( localImagesDir, remoteImageDir)