How i can get fat32 attributes (like archived, hidden...) in linux without spawning a new process with fatattr utility call ? May be there is python binding for it or for linux/fs functions (fat_ioctl_get_attributes, http://www.cs.fsu.edu/~baker/devices/lxr/http/source/linux/fs/fat/file.c). Or maybe it can be done with python-xattr ?
As you can see in the function name, the kernel function fat_ioctl_get_attributes is called from userspace via an ioctl, and I'm not aware of any other binding. Therefore, you can simply read the attributes by calling ioctl yourself, like this:
import array
import fcntl
import os
FAT_IOCTL_GET_ATTRIBUTES = 0x80047210
FATATTR_BITS = 'rhsvda67'
def get_fat_attrs(fn):
fd = os.open(fn, os.O_RDONLY)
try:
buf = array.array('L', [0])
try:
fcntl.ioctl(fd, FAT_IOCTL_GET_ATTRIBUTES, buf, True)
except IOError as ioe:
if ioe.errno == 25: # Not a FAT volume
return None
else:
raise
return buf[0]
finally:
os.close(fd)
if __name__ == '__main__':
import sys
for fn in sys.argv[1:]:
attrv = get_fat_attrs(fn)
if attrv is None:
print(fn + ': Not on a FAT volume')
continue
s = ''.join((fb if (1 << idx) & attrv else ' ')
for idx,fb in enumerate(FATATTR_BITS))
print(fn + ': ' + s)
Related
I'm trying to create a list of alll usb mass storage devices with their VendorIf, the ProductId and the SerialNumber.
Therefore I use the pyUsb module and run the following program.
import sys
import usb
import usb.core
import usb.util
devs = usb.core.find(find_all=True)
nCount=0
for dev in devs:
try:
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:
sys.stdout.write("SerialNbr = " + usb.util.get_string(dev,dev.iSerialNumber,None) + '\n')
else:
sys.stdout.write("SerialNbr = none" + '\n')
sys.stdout.write('\n')
except usb.core.USBError:
pass
In generally the script works. Depending on the device I get outputs like this:
USB device USB DISK
-------
VendorId = 0x90c
ProductId = 0x2000
SerialNbr = none
But with various devices I get the following error:
File
"C:\Users\UerXy\AppData\Local\Programs\Python\Python39\lib\site-packages\usb\backend\libusb1.py",
line 600, in _check
raise NotImplementedError(_strerror(ret)) NotImplementedError: Operation not supported or unimplemented on this platform
When debugging the code, the error occures when it tries to read the string descriptor using the function usb.util.get_string()
I read somewhere, that the function is dependant on the driver.
Is this true? Isn't it possible to read the serial number of any given usb-device without taking care of the used usb-driver?
How can this error be solved and the descriptors be read from every device?
You can use the following code to get the information of all connected drives (flash memory and hdd).
import os
os.system('echo list volume > Ravi.txt')
path1 = os.path.join(os.getcwd(),"Ravi.txt")
os.system('diskpart /s '+path1+' > logfile.txt')
path2 = os.path.join(os.getcwd(),"logfile.txt")
Str = open(path2).read()
Str = Str.split('\n')
matching = [s for s in Str if "Removable" in s]
for i in matching:
i = ' '.join(i.split())
i = i.split(" ")
print(i)
import subprocess
serials = subprocess.check_output('wmic diskdrive get SerialNumber').decode().split('\n')[1:]
serials = [s.strip() for s in serials if s.strip()]
After running this code, two txt files will be created in the current location, in which the desired information is written
I have the following code:
#!/usr/bin/env python
# coding=utf-8
import threading
import requests
import Queue
import sys
import re
#ip to num
def ip2num(ip):
ip = [int(x) for x in ip.split('.')]
return ip[0] << 24 | ip[1] << 16 | ip[2] << 8 | ip[3]
#num to ip
def num2ip(num):
return '%s.%s.%s.%s' % ((num & 0xff000000) >> 24,(num & 0x00ff0000) >> 16,(num & 0x0000ff00) >> 8,num & 0x000000ff)
def ip_range(start, end):
return [num2ip(num) for num in range(ip2num(start), ip2num(end) + 1) if num & 0xff]
def bThread(iplist):
threadl = []
queue = Queue.Queue()
for host in iplist:
queue.put(host)
for x in xrange(0, int(SETTHREAD)):
threadl.append(tThread(queue))
for t in threadl:
t.start()
for t in threadl:
t.join()
#create thread
class tThread(threading.Thread):
def __init__(self, queue):
threading.Thread.__init__(self)
self.queue = queue
def run(self):
while not self.queue.empty():
host = self.queue.get()
try:
checkServer(host)
except:
continue
def checkServer(host):
ports = [80]
for k in ports:
try:
aimurl = "http://"+host+":"+str(k)
response = requests.get(url=aimurl,timeout=3)
serverText = response.headers['server']
if (response.status_code) == 403:
print "-"*50+"\n"+aimurl +" Server: "+serverText
except:
pass
if __name__ == '__main__':
print '\n############# CDN IP #############'
print ' '
print '################################################\n'
global SETTHREAD
try:
SETTHREAD = sys.argv[2]
iplist = []
file = open(sys.argv[1], 'r')
tmpIpList = file.readlines()
for ip in tmpIpList:
iplist.append(ip.rstrip("\n"))
print '\nEscaneando '+str(len(iplist))+" IP's...\n"
bThread(iplist)
except KeyboardInterrupt:
print 'Keyboard Interrupt!'
sys.exit()
This script works as follows, a range of ip is entered:
python2 script.py 104.0.0.0-104.0.1.255 100 (100 is the number of threads)
I want to add support so that it reads the ip of a file, and that the range also works.
python2 script.py ips.txt 100
I tried this:
file = open(sys.argv[1], 'r')
iplist = file.readlines()
But it does not work.
Edit1: added file reading code recommended by user Syed Hasan, the problem seems to be the bThread(iplist) function
I assume you're attempting to use 'iplist' the same way as your CLI input was attempting to parse it. However, the readlines function simply reads the entire file at once and appends a newline (\n) at the end (provided you do format the IPs with a succeeding newline character).
Currently, you should be getting a list of IPs with a succeeding newline character. Try removing it from the rightmost end using rstrip:
file = open(sys.argv[1], 'r')
tmpIpList = file.readlines()
for ip in tmpIpList:
iplist.append(ip.rstrip("\n"))
How you switch between the two modes is a challenge you should attempt to solve. Perhaps use command-line parameter support to identify the mode of operations (look into the argparse library).
i know that a lot of people have asked related questions but please help me out. I am trying to replicate an opensource temperature control lab i found online. I wanted to run it on Raspberry Pi.
This is the error i keep getting:
Traceback (most recent call last):
File "/home/pi/Desktop/Python/test_Temperature.py", line 14, in <module>
print('Temperature 1: ' + str(a.T1) + ' degC')
File "/home/pi/Desktop/Python/tclab.py", line 26, in T1
self._T1 = float(self.read('T1'))
TypeError: float() argument must be a string or a number, not 'NoneType'
The code that generates it is this:
import tclab
import numpy as np
import time
try:
# Connect to Arduino
a = tclab.TCLab()
# Get Version
print(a.version)
# Temperatures
print('Temperatures')
print('Temperature 1: ' + str(a.T1) + ' degC')
print('Temperature 2: ' + str(a.T2) + ' degC')
# Turn LED on
print('LED On')
a.LED(100)
# Turn on Heaters (0-100%)
print('Turn On Heaters (Q1=90%, Q2=80%)')
a.Q1(90.0)
a.Q2(80.0)
# Sleep (sec)
time.sleep(60.0)
# Turn Off Heaters
print('Turn Off Heaters')
a.Q1(0.0)
a.Q2(0.0)
# Temperatures
print('Temperatures')
print('Temperature 1: ' + str(a.T1) + ' degC')
print('Temperature 2: ' + str(a.T2) + ' degC')
# Allow user to end loop with Ctrl-C
except KeyboardInterrupt:
# Disconnect from Arduino
a.Q1(0)
a.Q2(0)
print('Shutting down')
a.close()
# Make sure serial connection still closes when there's an error
except:
# Disconnect from Arduino
a.Q1(0)
a.Q2(0)
print('Error: Shutting down')
a.close()
raise
I believe the code seeks to communicate with another python file with the below code:
import sys
import time
import numpy as np
try:
import serial
except:
import pip
pip.main(['install','pyserial'])
import serial
from serial.tools import list_ports
class TCLab(object):
def __init__(self, port=None, baud=9600):
if (sys.platform == 'darwin') and not port:
port = '/dev/ttyACM1'
def stop(self):
return self.read('X')
def version(self):
return self.read('VER')
#property
def T1(self):
self._T1 = float(self.read('T1'))
return self._T1
#property
def T2(self):
self._T2 = float(self.read('T2'))
return self._T2
def LED(self,pwm):
pwm = max(0.0,min(100.0,pwm))/2.0
self.write('LED',pwm)
return pwm
def Q1(self,pwm):
pwm = max(0.0,min(100.0,pwm))
self.write('Q1',pwm)
return pwm
def Q2(self,pwm):
pwm = max(0.0,min(100.0,pwm))
self.write('Q2',pwm)
return pwm
# save txt file with data and set point
# t = time
# u1,u2 = heaters
# y1,y2 = tempeatures
# sp1,sp2 = setpoints
def save_txt(self,t,u1,u2,y1,y2,sp1,sp2):
data = np.vstack((t,u1,u2,y1,y2,sp1,sp2)) # vertical stack
data = data.T # transpose data
top = 'Time (sec), Heater 1 (%), Heater 2 (%), ' \
+ 'Temperature 1 (degC), Temperature 2 (degC), ' \
+ 'Set Point 1 (degC), Set Point 2 (degC)'
np.savetxt('data.txt',data,delimiter=',',header=top,comments='')
def read(self,cmd):
cmd_str = self.build_cmd_str(cmd,'')
try:
self.sp.write(cmd_str.encode())
self.sp.flush()
except Exception:
return None
return self.sp.readline().decode('UTF-8').replace("\r\n", "")
def write(self,cmd,pwm):
cmd_str = self.build_cmd_str(cmd,(pwm,))
try:
self.sp.write(cmd_str.encode())
self.sp.flush()
except:
return None
return self.sp.readline().decode('UTF-8').replace("\r\n", "")
def build_cmd_str(self,cmd, args=None):
"""
Build a command string that can be sent to the arduino.
Input:
cmd (str): the command to send to the arduino, must not
contain a % character
args (iterable): the arguments to send to the command
"""
if args:
args = ' '.join(map(str, args))
else:
args = ''
return "{cmd} {args}\n".format(cmd=cmd, args=args)
def close(self):
try:
self.sp.close()
print('Arduino disconnected successfully')
except:
print('Problems disconnecting from Arduino.')
print('Please unplug and reconnect Arduino.')
return True
I do not know my around python codes yet so a very clear 'for dummy class' explanation of the solution would really help. Thanks guys.
This is the read() function:
def read(self,cmd):
cmd_str = self.build_cmd_str(cmd,'')
try:
self.sp.write(cmd_str.encode())
self.sp.flush()
except Exception:
return None
return self.sp.readline().decode('UTF-8').replace("\r\n", "")
One of the things it can return is None as you can see in the return None line. If that happens, then your line:
float(self.read('T1'))
will fail, because it will try to convert None into a float, and that gives the error you're getting.
I would like to read Windows' event log. I am not sure if it's the best way but I would like to use the pywin32 -> win32evtlog module to do so. First and foremost is it possible to read logs from Windows 7 using this library and if so how to read events associated with applications runs (running an .exe must leave a trace in the event log in windows i guess).
I have managed to find some little example on the net but it's not enough for me and the documentation isn't well written unfortunately ;/
import win32evtlog
hand = win32evtlog.OpenEventLog(None,"Microsoft-Windows-TaskScheduler/Operational")
print win32evtlog.GetNumberOfEventLogRecords(hand)
you can find plenty of demos related to the winapi in your C:\PythonXX\Lib\site-packages\win32\Demos folder. In this folder you'll find a script named eventLogDemo.py. There you can see how to use win32evtlog module. Just start this script with eventLogDemo.py -v and you will get prints from your Windows event log with logtype Application.
In case you can't find this script:
import win32evtlog
import win32api
import win32con
import win32security # To translate NT Sids to account names.
import win32evtlogutil
def ReadLog(computer, logType="Application", dumpEachRecord = 0):
# read the entire log back.
h=win32evtlog.OpenEventLog(computer, logType)
numRecords = win32evtlog.GetNumberOfEventLogRecords(h)
# print "There are %d records" % numRecords
num=0
while 1:
objects = win32evtlog.ReadEventLog(h, win32evtlog.EVENTLOG_BACKWARDS_READ|win32evtlog.EVENTLOG_SEQUENTIAL_READ, 0)
if not objects:
break
for object in objects:
# get it for testing purposes, but dont print it.
msg = win32evtlogutil.SafeFormatMessage(object, logType)
if object.Sid is not None:
try:
domain, user, typ = win32security.LookupAccountSid(computer, object.Sid)
sidDesc = "%s/%s" % (domain, user)
except win32security.error:
sidDesc = str(object.Sid)
user_desc = "Event associated with user %s" % (sidDesc,)
else:
user_desc = None
if dumpEachRecord:
print "Event record from %r generated at %s" % (object.SourceName, object.TimeGenerated.Format())
if user_desc:
print user_desc
try:
print msg
except UnicodeError:
print "(unicode error printing message: repr() follows...)"
print repr(msg)
num = num + len(objects)
if numRecords == num:
print "Successfully read all", numRecords, "records"
else:
print "Couldn't get all records - reported %d, but found %d" % (numRecords, num)
print "(Note that some other app may have written records while we were running!)"
win32evtlog.CloseEventLog(h)
def usage():
print "Writes an event to the event log."
print "-w : Dont write any test records."
print "-r : Dont read the event log"
print "-c : computerName : Process the log on the specified computer"
print "-v : Verbose"
print "-t : LogType - Use the specified log - default = 'Application'"
def test():
# check if running on Windows NT, if not, display notice and terminate
if win32api.GetVersion() & 0x80000000:
print "This sample only runs on NT"
return
import sys, getopt
opts, args = getopt.getopt(sys.argv[1:], "rwh?c:t:v")
computer = None
do_read = do_write = 1
logType = "Application"
verbose = 0
if len(args)>0:
print "Invalid args"
usage()
return 1
for opt, val in opts:
if opt == '-t':
logType = val
if opt == '-c':
computer = val
if opt in ['-h', '-?']:
usage()
return
if opt=='-r':
do_read = 0
if opt=='-w':
do_write = 0
if opt=='-v':
verbose = verbose + 1
if do_write:
ph=win32api.GetCurrentProcess()
th = win32security.OpenProcessToken(ph,win32con.TOKEN_READ)
my_sid = win32security.GetTokenInformation(th,win32security.TokenUser)[0]
win32evtlogutil.ReportEvent(logType, 2,
strings=["The message text for event 2","Another insert"],
data = "Raw\0Data".encode("ascii"), sid = my_sid)
win32evtlogutil.ReportEvent(logType, 1, eventType=win32evtlog.EVENTLOG_WARNING_TYPE,
strings=["A warning","An even more dire warning"],
data = "Raw\0Data".encode("ascii"), sid = my_sid)
win32evtlogutil.ReportEvent(logType, 1, eventType=win32evtlog.EVENTLOG_INFORMATION_TYPE,
strings=["An info","Too much info"],
data = "Raw\0Data".encode("ascii"), sid = my_sid)
print("Successfully wrote 3 records to the log")
if do_read:
ReadLog(computer, logType, verbose > 0)
if __name__=='__main__':
test()
I hope this script fits your needs
I have written this code so far;
from _winreg import *
def val2addr(val):
addr = ''
for ch in val:
addr += '%02x '% ord(ch)
addr = addr.strip(' ').replace(' ', ':')[0:17]
return addr
def printNets():
net = "SOFTWARE\Microsoft\Windows NT\CurrentVersion"+\
"\NetworkList\Signatures\Unmanaged"
key = OpenKey(HKEY_LOCAL_MACHINE, net)
print '\n[*] Networks You Have Joined.'
for i in range(100):
try:
guid = EnumKey(key, i)
netKey = OpenKey(key, str(guid))
(n, addr, t) = EnumValue(netKey, 5)
(n, name, t) = EnumValue(netKey, 4)
macAddr = val2addr(addr)
netName = str(name)
print '[+] ' + netName + ' ' + macAddr
CloseKey(netKey)
except:
break
def main():
printNets()
if __name__ == "_main_":
main()
This script returns the MAC addresses and network names of all the WiFi networks you have joined.
It returns values from
Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows >NT\CurrentVersion\NetworkList\Signatures\Unmanaged\
I am on Windows 8.1 and I have checked through Regedit.exe to make sure this is the correct location for the info I am retrieving.
When I run this code it says "WindowsError: [Error 2] The system cannot find the file specified"
So what is it I am doing wrong?
P.S I am on Python 2.7.9
Full Traceback
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
printNets()
File "C:/Users/Nathaniel/Desktop/MacAddr Meta-Reader.py", line 13, in printNets
key = OpenKey(HKEY_LOCAL_MACHINE, net)
WindowsError: [Error 2] The system cannot find the file specified
You're probably using 32-bit Python on 64-bit Windows. In this case opening HKLM\SOFTWARE gets redirected to HKLM\SOFTWARE\Wow6432Node. You have to specify otherwise if you want the 64-bit key. For example:
key = OpenKey(HKEY_LOCAL_MACHINE, net, 0,
KEY_READ | KEY_WOW64_64KEY)
Note that for subkeys opened relative to this key object, it isn't strictly necessary to specify KEY_WOW64_64KEY.
I ported your code to run in both Python 2 and 3, added iterators, and eliminated the hard-coded range and index values. Maybe you'll find it helpful:
from __future__ import print_function
import itertools
try:
from winreg import *
except ImportError: # Python 2
from _winreg import *
KEY_READ_64 = KEY_READ | KEY_WOW64_64KEY
ERROR_NO_MORE_ITEMS = 259
def iterkeys(key):
for i in itertools.count():
try:
yield EnumKey(key, i)
except OSError as e:
if e.winerror == ERROR_NO_MORE_ITEMS:
break
raise
def itervalues(key):
for i in itertools.count():
try:
yield EnumValue(key, i)
except OSError as e:
if e.winerror == ERROR_NO_MORE_ITEMS:
break
raise
def val2addr(val):
return ':'.join('%02x' % b for b in bytearray(val))
NET_UNMANAGED = (r"SOFTWARE\Microsoft\Windows NT\CurrentVersion"
r"\NetworkList\Signatures\Unmanaged")
def printNets(keystr=NET_UNMANAGED):
key = OpenKey(HKEY_LOCAL_MACHINE, keystr, 0, KEY_READ_64)
print('\n[*] Networks You Have Joined.')
for guid in iterkeys(key):
netKey = OpenKey(key, guid)
netName, macAddr = '', ''
for name, data, rtype in itervalues(netKey):
if name == 'FirstNetwork':
netName = data
elif name == 'DefaultGatewayMac':
macAddr = val2addr(data)
if netName:
print('[+]', netName, macAddr)
CloseKey(netKey)
CloseKey(key)
The key's security descriptor only allows access to administrators and the netprofm service, as shown below. So you either need to run the script from an elevated command prompt or use a technique to have the script autoelevate.
C:\>set NT=HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion
C:\>accesschk -qldk "%NT%\NetworkList\Signatures\Unmanaged"
HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\
NetworkList\Signatures\Unmanaged
DESCRIPTOR FLAGS:
[SE_DACL_PRESENT]
[SE_DACL_PROTECTED]
OWNER: BUILTIN\Administrators
[0] ACCESS_ALLOWED_ACE_TYPE: NT SERVICE\netprofm
[CONTAINER_INHERIT_ACE]
[INHERITED_ACE]
KEY_QUERY_VALUE
KEY_CREATE_LINK
KEY_CREATE_SUB_KEY
KEY_ENUMERATE_SUB_KEYS
KEY_NOTIFY
KEY_SET_VALUE
READ_CONTROL
DELETE
[1] ACCESS_ALLOWED_ACE_TYPE: BUILTIN\Administrators
[CONTAINER_INHERIT_ACE]
[INHERITED_ACE]
KEY_ALL_ACCESS
C:\>sc qdescription netprofm
[SC] QueryServiceConfig2 SUCCESS
SERVICE_NAME: netprofm
DESCRIPTION: Identifies the networks to which the computer has
connected, collects and stores properties for these networks,
and notifies applications when these properties change.
Do you have administrator privileges? I tried walking down the tree with "reg query" to make sure that I didn't have a spelling problem and when I got to "NetworkList" I got an Access denied error. I changed to administrator privileges and everything was fine.
reg query "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\NetworkList
ERROR: Access is denied.