How do you print network history using _winreg in Python? - python

I'm trying to print out the network history saved in the Windows Registry and am running into a snag.
I have two functions. One to convert the binary text, and the second to get the actual data.
Here is what I have:
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 key
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)
macAddr = val2addr(addr)
netName = str(name)
print '[+] ' + netName + ' ' + macAddr
CloseKey(netKey)
except:
break
I believe the error is in this guid value:
for i in range(100):
try:
guid = EnumKey(key, i)
netKey = OpenKey(key, str(guid))
(n, addr, t) = EnumValue(netKey, 5)
When I run the "try" subcode by itself it throws up a:
[ERROR 259] no more data available
pointing to the guid value.
I think that is where I am stuck. I'm having trouble finding the error because it just gets thrown to the except code, and thus not giving me any feedback.
Please help!!!
EDIT: From what I am digging up it may be due to running 32bit Python on a 64bit system. Still digging though.

When I came across the 32/64 bit problem I got round it by using code similar to this
import winreg
HKLM =winreg.HKEY_LOCAL_MACHINE
bb = r"SOFTWARE\Microsoft\Windows NT\CurrentVersion\NetworkList\Signatures\Unmanaged"
abc = winreg.OpenKeyEx(HKLM, bb,0,(winreg.KEY_WOW64_64KEY + winreg.KEY_ALL_ACCESS))
efg = winreg.EnumKey(abc,0)
z = winreg.OpenKeyEx(abc,str(efg))
q = winreg.QueryValueEx(z,"Description")[0]
print (q)
q = winreg.QueryValueEx(z,"DefaultGatewayMac")[0]
print (q)
Hope this helps pointing you in the right direction

Related

Python - getting SerialNumber of usb-devices with pyUsb in windows

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

De/encoding hex-numbers with python

I'm currently trying to get MAC-Addresses that are saved on my device using python3.8 and I'm getting the following error:
non-hexadecimal number found in fromhex() arg at position 3
I know it's a decoding error.
Here is the Code:
def val2addr(val):
if val:
address = ""
for ch in val:
if(not int(ch)):
address += ':'.join(format(s, '02x') for s in bytes.fromhex(str(ch))).replace("\0", "")
address = address.strip(' ').replace(' ', ':')[0: 17]
else:
address += str(ch)
return address + ':'.join(format(s, '02x') for s in bytes.fromhex(str(ch))).replace("\0", "")
return "[!] No MAC [!]"
def print_networks():
net = u"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion"+\
"\\NetworkList\\Signatures\\Unmanaged"
print(str(HKEY_LOCAL_MACHINE) + net)
key = OpenKey(HKEY_LOCAL_MACHINE, net, 0, (KEY_WOW64_64KEY + KEY_READ))
print('\n[*] Networks You have Joined:\n')
for network in range(100):
try:
guid = EnumKey(key, network)
netkey = OpenKey(key, str(guid))
mac = QueryValueEx(netkey, 'DefaultGatewayMac')[0]
mac = val2addr(mac)
network_name = QueryValueEx(netkey, 'Description')[0]
print("[+] Network Name: " + network_name + "[+] Mac: " + mac)
CloseKey(netkey)
except Exception as e:
print(e)
break
def main():
print_networks()
if __name__ == '__main__':
main()
I almost tried every solution I could find here or on the internet and none of them worked for me!
Thank you in advance for your help!
The fromhex function expects a string that's at least two digits long (since each individual byte is two hex digits), and you're only passing it a single character. If your intent is to zero-pad the input digit, you can do that by prepending "0" to it like this:
def val2addr(val: str) -> str:
if val:
address = ""
for ch in val:
if not int(ch):
address += ':'.join(
format(s, '02x') for s in bytes.fromhex("0"+ch)
).replace("\0", "")
address = address.strip(' ').replace(' ', ':')[0:17]
else:
address += str(ch)
return address + ':'.join(
format(s, '02x') for s in bytes.fromhex("0"+ch)
).replace("\0", "")
return "[!] No MAC [!]"
print(val2addr("1234")) # prints "123404"

While calling function with pool, It shows the variable is not defined which is there in main (global)

May be my question looks simple (or the Bug might be minor) but I could not be able find the bug, really I struggled a lot to figure out the issue.
I've created a Framework to Extract the Data from Salesforce with Simple Salesforce package, but I've encountered with the bug when I'm using multiprocessing.
My code is pretty much straight forward but tedious. I don't want to paste entire code here, So here is my Code from my GitHub.
Issue:
When I'm calling this Extract Data function with Pool, the variable which is there in the __name__ == '__main__' is not working.
In Other words I'm getting, NameError: name 'SFAPI' is not defined - But It's there in the main as Global Variable and It's working without pool (A single call).
Execution Example:
python "E:\Documents\myPy\SF Project\sf_extraction.py" -pr data_extraction -tn Opportunity Account
Small Snippet from my code, where I'm getting issues:
def ExtractData(table_name):
logging.info('Extract Data for Table Name: ' + table_name + ' at ' + getCurrDatetime())
try:
rec_count = getRecordCount(table_name)
print(rec_count)
if int(rec_count) == 0:
logging.info('There is no data to Extract for {}'.format(table_name))
else:
soql = SFAPI.CreateSOQL(table_name)
data = SFAPI.ExecuteSOQL(soql, is_count=0)
extract_file_nm = table_name + '_' + db_name + '_' + sc_name + '_' + curr_datetime + '.csv'
print(data)
print(type(data))
extract_file = os.path.expanduser(os.path.join(script_path,extract_file_nm))
data.to_csv(extract_file, index=False)
logging.info('Data has been extrcated as {} at {}'.format(extract_file, getCurrDatetime()))
except Exception as e:
logging.info('Error in Extraction')
err_msg = "FATAL_ERROR: In the ExtractData Function : {0}\n\n{1}".format(e, traceback.format_exc())
raise Exception(str(err_msg))
Place or Snippet from where I'm calling this:
if __name__ == '__main__':
try:
SFAPI = SalesforceAPICall(username=config['username'],
password=config['password'],
security_token=config['sf_token'],
)
if len(table_name) != 0 and 'data_extraction' in process_nm:
try:
if len(table_name) == 1:
print(table_name[0])
ExtractData(table_name[0])
if type(table_name) == list and len(table_name) > 1:
#p = Pool(processes=int(processes))
print('Calling Pool : ' + str(os.cpu_count()))
#out = p.map(ExtractData, table_name)
#p.close()
#p.join()
p = Pool()
print(table_name)
x = p.map(ExtractData, table_name)
x.get()
p.close()
p.join()
except Exception as e:
if len(table_name) > 1:
p.terminate()
p.join()
logging.error("Process Failed - " + str(e))
except Exception as e:
chk_err('FATAL_ERROR: ' + " from main exception : {0}\n\n{1}".format(e, traceback.format_exc()))
You can very well refer my code in GitHub if it looks clumsy or if you feel this is not enough amount of information to fix.
Again it might be a small Bug, Hope You Understand what I'm trying to convey !!! Thanks in
Advance !!!
Regards,
Parvathirajan Natarajan

create a range from arguments

Really new to python but I'm trying to practice and do things using python to make the learning experience interesting, I am trying to do a a scanner for a range of ports, but I want to specify the ports as a cli argument. However, when I put them on the range, nothing happens so I think I'm not parsing the arguments properly, how do I do this?
Here is part of my code:
host = sys.argv[1]
first_port = sys.argv[2]
ending_port = sys.argv[3]
print "Checking ports on the range of " + start_port + " to " + end_port
try:
for port in range(first_port, ending_port):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = s.connect_ex((host, port))
if result == 0:
print "--> Port " + str(port) + "open"
s.close()
except:
pass
If I put range(1, 1024) it does work but is not liking the way I pass my arguments. Also, I tried converting to int with first_port = int(sys.argv[2]) for example, but again nothing happens. What am I missing on this?
Changing
first_port = sys.argv[2]
ending_port = sys.argv[3]
print "Checking ports on the range of " + start_port + " to " + end_port
to
first_port = int(sys.argv[2])
ending_port = int(sys.argv[3])
print "Checking ports on the range of {} to {}".format(first_port, ending_port)
yields the correct behavior. Also, you probably want to range on
for port in range(first_port, ending_port+1):
since the end of range is non-inclusive.
The big lesson here (in my opinion) is don't use pass in an except unless you explicitly know it should be passed. If you had some error with your input params then you would just be swallowing the exception instead of getting a helpful stacktrace / error message.

How do I use Python to retrieve Registry values?

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.

Categories