Address of the PATH key in the Windows 10 registry? - python

What is the correct address in the Windows 10 Registry from which to get and set the PATH variable?
When I run the Python program below, none of the following three options work:
from winreg import *
#The following line (uncommented) gives a list of things including Environment
keyVal = r"SYSTEM\CurrentControlSet\Control\Session Manager"
#The following line (uncommendted) gives an empty list of results (nothing)
#keyVal = r"SYSTEM\CurrentControlSet\Control\Session Manager\Environment"
#The following line (uncommented) gives an error message as follows: "FileNotFoundError: [WinError 2] The system cannot find the file specified"
#keyVal = r"SYSTEM\CurrentControlSet\Control\Session Manager\Environment\Path"
aKey = OpenKey(HKEY_LOCAL_MACHINE, keyVal, 0, KEY_ALL_ACCESS)
try:
i = 0
while True:
asubkey = EnumKey(aKey, i)
print(asubkey)
i += 1
except WindowsError:
pass
Windows CMD is being run as administrator when the Python code above is called. I am running Windows CMD as an administrator in hopes of avoiding permissions issues when running the above script to access registry keys.
Note: When I type regedit into the Windows Start Menu, and I drill down to Computer\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment , I am able to see a properly-populated Path variable. Even though the error shown above is given when I try to access this programmatically as an administrator.
2nd Note: When I try the code at this link per #SimonCrane 's suggestion, and call the function with open_env_registry_key('system') , the result is an error when SYS_ENV_SUBPATH = r"SYSTEM\CurrentControlSet\Control\Session Manager\Environment\Path", or no results at all when using SYS_ENV_SUBPATH = r"SYSTEM\CurrentControlSet\Control\Session Manager\Environment" or SYS_ENV_SUBPATH = r"SYSTEM\CurrentControlSet\Control\Session Manager",

Related

Flask The system cannot find the path specified: '130.127.5.9'

I've just started experimenting with flask and
I am trying to list a network driver using it. This is the command that I type on my browser. But I get an error that it cant find the path
http://127.0.0.1:5000/130.13.5.8/D/dir/
The function works for local drivers without an issue
I know why it fails. It needs 2 '\' before the actual ip or 4 '\\' .
But when I try http://127.0.0.1:5000/////130.13.5.8/D/dir/
it doesnt work.
I even tried %F%F it also doesn't seem to do the trick.
#app.route('/<path:filepath>/dir/')
def get_dir(filepath):
dir_listing = ''
for entry in os.listdir(filepath):
entry_type = 'dir' if os.path.isdir(os.path.join(filepath, entry)) else 'file'
dir_listing += '{entry_name}|{entry_type}|'.format(entry_name=entry, entry_type=entry_type)
return dir_listing
For anyone having the same issue my workaround is the following
from ipaddress import ip_address
try:
ip_address(filepath.split('/')[0])
filepath = '\\\\{filepath}'.format(filepath=filepath)
except ValueError as e:
pass

How to get default browser name using python?

Following solutions (actually it is only one) doesn't work to me :
How to get a name of default browser using python
How to get name of the default browser in windows using python?
Solution was:
from _winreg import HKEY_CURRENT_USER, OpenKey, QueryValue
# In Py3, this module is called winreg without the underscore
with OpenKey(HKEY_CURRENT_USER,
r"Software\Classes\http\shell\open\command") as key:
cmd = QueryValue(key, None)
But unfortunately, in Windows 10 Pro I don't have targeted registry value. I've tried to find alternative keys in Regedit, but no luck.
Please take a look, what my registry virtually contains:
The following works for me on Windows 10 pro:
from winreg import HKEY_CURRENT_USER, OpenKey, QueryValueEx
reg_path = r'Software\Microsoft\Windows\Shell\Associations\UrlAssociations\https\UserChoice'
with OpenKey(HKEY_CURRENT_USER, reg_path) as key:
print(QueryValueEx(key, 'ProgId'))
Result (first with Chrome set as default, then with IE):
$ python test.py
('ChromeHTML', 1)
$ python test.py
('IE.HTTPS', 1)
Please check for the key in windows 10
HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\Shell\Associations\URLAssociations(http|https)\UserChoice
def get_windows_default_browser_launch():
""" On windows, return the default browser for 'https' urls
returns: example '"C:\Program Files\Mozilla Firefox\firefox.exe" -osint -url "%1"'
"""
import winreg
key = winreg.OpenKey(winreg.ConnectRegistry(None, winreg.HKEY_CURRENT_USER), r"Software\Microsoft\Windows\Shell\Associations\UrlAssociations\https\UserChoice")
prog_id, _ = winreg.QueryValueEx(key, "ProgId")
key = winreg.OpenKey(winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE), r"SOFTWARE\Classes\{}\shell\open\command".format(prog_id))
launch_string, _ = winreg.QueryValueEx(key, "") # read the default value
return launch_string
Windows 10 Python3 , may want to change the key for 'http' not https, but this is my code verbatim as my context is of a secured server. I wanted the browser binary name and path, which is just one more line.

Error when using os.stat - Python

Solved: Adding an os.chdir(myArg) resolved the issue.
I'm getting an error when trying to run the following code on anything other than my home directory or files/direcs that I own.
FileNotFoundError: [Errno 2] No such file or directory:
I created a file in root and changed ownership on the file to pi:pi (user running the script). If I specify that file directly, it works, however if I run the script on "/", it will not read that or any other file/direc. I also created a directory /tempdir_delete/ and changed ownership to pi:pi.. If I run the script specifically on "/tempdir_delete/*", it works, but if I leave off the * it fails.
Why does it fail on all except /home/pi/ or files that I explicitly specify and own? It's running the stat as user pi, which is granted by sudo to perform the stat. Also, why do I have to specify the file that I own explicitly? Shouldn't it see that file in root and work because I own it?
import os
import re
import sys
import pwd
myReg = re.compile(r'^\.')
myUID = os.getuid()
myArg = sys.argv[1]
print(os.getuid())
print(pwd.getpwuid(int(myUID)))
print(myArg)
def getsize(direct):
if os.path.isfile(direct) == True:
statinfo = os.stat(myArg)
print(str(statinfo.st_size))
else:
for i in os.listdir(direct):
try:
statinfo = os.stat(i)
if myReg.search(i):
continue
else:
print(i + ' Size: ' + str(statinfo.st_size))
except:
print('Exception occurred, can't read.')
continue
getsize(myArg)
Solved. Adding an os.chdir(myArg) worked to resolve the issue.

Nmap module issues in python

I have installed nmap.exe and the nmap module. I am not sure how to configure the nmap path though.
The block of code where you enter the nmap path is as follows
class PortScanner(object):
"""
PortScanner class allows to use nmap from python
"""
def __init__(self, nmap_search_path=('nmap','/usr/bin/nmap','/usr/local/bin/nmap','/sw/bin/nmap','/opt/local/bin/nmap') ):
"""
Initialize PortScanner module
* detects nmap on the system and nmap version
* may raise PortScannerError exception if nmap is not found in the path
:param nmap_search_path: tupple of string where to search for nmap executable. Change this if you want to use a specific version of nmap.
:returns: nothing
"""
self._nmap_path = 'C:/Program Files (x86)/Nmap/' # nmap path
self._scan_result = {}
self._nmap_version_number = 0 # nmap version number
self._nmap_subversion_number = 0 # nmap subversion number
self._nmap_last_output = '' # last full ascii nmap output
is_nmap_found = False # true if we have found nmap
self.__process = None
# regex used to detect nmap
regex = re.compile('Nmap version [0-9]*\.[0-9]*[^ ]* \( http://.* \)')
# launch 'nmap -V', we wait after 'Nmap version 5.0 ( http://nmap.org )'
# This is for Mac OSX. When idle3 is launched from the finder, PATH is not set so nmap was not found
for nmap_path in nmap_search_path:
try:
p = subprocess.Popen([nmap_path, '-V'], bufsize=10000, stdout=subprocess.PIPE)
except OSError:
pass
else:
self._nmap_path = nmap_path # save path
break
else:
raise PortScannerError('nmap program was not found in path. PATH is : {0}'.format(os.getenv('PATH')))
I placed the path in the self._nmap_path variable. However, it does not seem to work.
Could anyone with experience in nmap help me? How do I get started in nmap? I have researched this for hours but have still not come up with an answer.
The error I receive is
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
nmap.PortScanner()
File "C:\Python33\Lib\site-packages\nmap\nmap.py", line 192, in __init__
raise PortScannerError('nmap program was not found in path')
nmap.PortScannerError: 'nmap program was not found in path'
It looks like your environment path is not setup correctly.
If you open the C:\Python33\Lib\site-packages\nmap\nmap.py file for editing and look at line 192. Where is it looking?
It might be worth simply reinstalling with the self installer, the installer should set the path variables for you.
http://nmap.org/book/inst-windows.html

Python: WindowsError when editing Registry values using _winreg on Windows 7

I am trying to execute this script by Ned Batchelder to switch .py file association between my two Python installations on Windows. This Python script uses the _winreg module (winreg in Python 3.x) to edit certain Registry values (the path and value pairs modified can be seen in the todo list in the script).
I execute this script as follows:
> SwitchPy.py "C:\Program Files\Python26"
I am getting the following error:
Traceback (most recent call last):
File "C:\Users\SuperUser\SwitchPy.py", line 30, in <module>
key = reg.OpenKey(classes_root, path, 0, reg.KEY_SET_VALUE)
WindowsError: [Error 5] Access is denied
I guessed that it could be something to do with account permissions. But, note that:
The account used above is part of the Administrators group and has admin privileges.
With the above account I can execute regedit.exe and manually set the values listed in the script without facing any permissions or access problems.
I am using Windows 7 and am part of a domain. Could any of this have something to do with this problem?
Does anyone have any clue about this error? How do I make this script run?
When I tried that one, I got "Path not found" error on Python.CompiledFile.
I checked it on my registry, it does not exist, not Windows 7 though.
So, I removed those lines of Python.CompiledFile and its running fine here, or
You could put try: except: On OpenKey and SetValue, not good idea though.
I was able to run the script by opening a command prompt using the "Run as Administrator".
It appears that you can only maintain HKEY_LOCAL_MACHINE entries if you run the script with elevated authorities.
Some of the HKEY_CLASSES_ROOT entries come from HKEY_LOCAL_MACHINE according to this MSDN link:
The HKEY_CLASSES_ROOT subtree is a view formed by merging HKEY_CURRENT_USER\Software\Classes and HKEY_LOCAL_MACHINE\Software\Classes
I updated the script to include the suggested try/except in addition to a few print statements for extra feedback.
Here is how I updated the script:
""" Change the .py file extension to point to a different
Python installation.
"""
import _winreg as reg
import sys
pydir = sys.argv[1]
todo = [
('Applications\python.exe\shell\open\command',
'"PYDIR\\python.exe" "%1" %*'),
('Applications\pythonw.exe\shell\open\command',
'"PYDIR\\pythonw.exe" "%1" %*'),
('Python.CompiledFile\DefaultIcon',
'PYDIR\\pyc.ico'),
('Python.CompiledFile\shell\open\command',
'"PYDIR\\python.exe" "%1" %*'),
('Python.File\DefaultIcon',
'PYDIR\\py.ico'),
('Python.File\shell\open\command',
'"PYDIR\\python.exe" "%1" %*'),
('Python.NoConFile\DefaultIcon',
'PYDIR\\py.ico'),
('Python.NoConFile\shell\open\command',
'"PYDIR\\pythonw.exe" "%1" %*'),
]
classes_root = reg.OpenKey(reg.HKEY_CLASSES_ROOT, "")
for path, value in todo:
print "Updating %s with %s" % (path, value.replace('PYDIR', pydir))
try:
key = reg.OpenKey(classes_root, path, 0, reg.KEY_SET_VALUE)
reg.SetValue(key, '', reg.REG_SZ, value.replace('PYDIR', pydir))
except:
print "Unable to maintain %s\n" % (path)

Categories

Resources