This question already has answers here:
Cross-platform way to check admin rights in a Python script under Windows?
(5 answers)
Closed 7 months ago.
I need a way to be able to check/test if admin privileges are need to access a folder in python. The one difference that is making me make whole new question about this is that the method should work even if the program has admin privileges.
In theory a function like this should be able to check if admin is required.
import os
def check_admin(path):
"""Returns `True` if admin privileges are required to access `path` and `False` if otherwise"""
try:
os.mkdir(os.path.join(path, "dkfjsdlfjsdkl"))
except PermissionError:
return True
else:
os.rmdir(os.path.join(path, "dkfjsdlfjsdkl"))
return False
And sure enough, doing check_admin(r'C:\Windows') will return True. So why am I asking this? Well, if you take that same program and run it as an admin, then check_admin(r'C:\Windows') returns False which is not what I want.
I have looked all over SO and none of the answers match the requirenments. Even os.access doesn't really do what I want (os.access(r"C:\Windows", os.X_OK) returns True).
So again, I need a way to be able to check/test if admin privileges are need to access a folder in python.
I am not sure that it works on Windows OS, but in Ubuntu you can try something like this:
import pathlib
pathlib.Path("/usr").owner()
pathlib.Path("/usr").group()
>> 'root'
>> 'root'
This question already has answers here:
Assign output of os.system to a variable and prevent it from being displayed on the screen [duplicate]
(8 answers)
Closed 5 years ago.
I want to write information about this tracing in file:
site = input('Input URL:')
trac = os.system('tracert '+site)
but trac equals 0 and I don't know how to get access to os.system() information.
Here :
trac = os.system('tracert '+site)
the return value is :
Linux
On Unix, the return value is the exit status of the process encoded in the format specified for wait().
or
Windows
On Windows, the return value is that returned by the system shell after running command, given by the Windows environment variable COMSPEC.
For more information about that see python's documentation about os.system.
But if you want to retrieve outputs of your system call then use subprocess.check_output method of subprocess module instead and try to change your code like that :
import subprocess
site = input('Input URL:')
trac = subprocess.check_output(["tracert", site])
# Do something else
Formerly you can did it with os.popen but since Python 2.6 it's deprecated :
Deprecated since version 2.6: All of the popen*() functions are obsolete. Use the subprocess module.
This question already has answers here:
Running shell command and capturing the output
(21 answers)
Closed 7 years ago.
I want protect my commercial application with hwid protection, I have this demidecode : http://gnuwin32.sourceforge.net/packages/dmidecode.htm return UUID of computer where run, the problem is need include this in python code ==> run in memory ==> return output and close, is possible this in python ?
or exist another method to get this UUID of computer ?
actual code :
subprocess.Popen('dmidecode.exe -s system-uuid'.split())
Use check_output to get the output of the shell command:
import subprocess
out = subprocess.check_output('dmidecode.exe -s system-uuid').decode('utf-8').strip()
print('system uuid:', out)
# system uuid: 6ba7b810-9dad-11d1-80b4-00c04fd430c8
This question already has answers here:
Checking for interactive shell in a Python script
(5 answers)
Closed 5 years ago.
Imagine a script is running in these 2 sets of "conditions":
live action, set up in sudo crontab
debug, when I run it from console ./my-script.py
What I'd like to achieve is an automatic detection of "debug mode", without me specifying an argument (e.g. --debug) for the script.
Is there a convention about how to do this? Is there a variable that can tell me who the script owner is? Whether script has a console at stdout? Run a ps | grep to determine that?
Thank you for your time.
Since sys.stdin will be a TTY in debug mode, you can use the os.isatty() function:
import sys, os
if os.isatty(sys.stdin.fileno()):
# Debug mode.
pass
else:
# Cron mode.
pass
You could add an environment variable to the crontab line and check, inside your python application, if the environment variable is set.
crontab's configuration file:
CRONTAB=true
# run five minutes after midnight, every day
5 0 * * * /path/to/your/pythonscript
Python code:
import os
if os.getenv('CRONTAB') == 'true':
# do your crontab things
else:
# do your debug things
Use a command line option that only cron will use.
Or a symlink to give the script a different name when called by cron. You can then use sys.argv[0]to distinguish between the two ways to call the script.
The Python pwd module provides access to getpwnam(3) POSIX API, which can be used to get the home directory for a particular user by username, as well determining if the username is valid at all. pwd.getpwnam will raise an exception if called with a non-existent username.
At first it seems like the same result can be achieved in a cross-platform manner via os.path.expanduser('~username'). However, it appears that with Python 2.6 on Windows XP this won't actually produce a failure for a non-existent username. Furthermore, on Python 2.5 on Windows XP, it seems to fail even for valid users.
Can this information be obtained reliably on Windows? How?
Reading the 2.6 documentation shows that os.path.expanduser() is broken on Windows:
On Windows, HOME and USERPROFILE will
be used if set, otherwise a
combination of HOMEPATH and HOMEDRIVE
will be used. An initial ~user is
handled by stripping the last
directory component from the created
user path derived above.
Say whaat? This assumes all user homes have to be under the same parent directory. Nuh-ugh!
It was a bit hard to dig but here is a solution that will look up a local user by given name:
from win32security import LookupAccountName, ConvertSidToStringSid
from _winreg import OpenKey, QueryValueEx, HKEY_LOCAL_MACHINE
def getUserDir(userName):
ssid = ConvertSidToStringSid(LookupAccountName(None, userName)[0])
key = OpenKey(HKEY_LOCAL_MACHINE, r'SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\\' + ssid)
return QueryValueEx(key, 'ProfileImagePath')[0]
I am new to Windows security... but reading MSDN and some blogs it seems to me that the way MS want us to handle other users specific data is by getting a user token.
There used to be a nice wiki of Keith Brown .Net Developers Guide to Windows Security... you can still find it in Google cache for "pluralsight keith.guidebook"
Case 1: If you don't have the user password:
For local accounts you can try reading the Windows registry as Nas Banov already suggested and there are some other recipes on SO or the Internet.
I am not sure how various Windows versions behaves for freshly create users ... those which have never performed an interactive session login ... does it automatically creates their registry, home folder and profile data?
I have done some tests on Windows XP and those registry keys were not present after creating an local account ... but in this case you can try to guess it based in All Users registry values ... or just fail :)
For desktop applications, when the application is running as a logged in user, I am using something like this to get the home folder.... and to get the equivalent of ~/.local I am using CSIDL_APPDATA, for roaming profiles, or just CSIDL_LOCAL_APPDATA.
from win32com.shell import shell, shellcon
# See microsoft references for further CSIDL constants
# http://msdn.microsoft.com/en-us/library/bb762181(VS.85).aspx
folder_name = shell.SHGetFolderPath(0, shellcon.CSIDL_PROFILE, 0, 0)
Reading Keith Brown article "How To Get A Token For A User" .. you can look for some other ways of getting an user token without a password...
Case 2: If you have the user password:
Reading the MSDN I got the impressing that if I have an user token, I can get its folders by calling something like the code below... but it did not worked for me. (not sure why)
token = win32security.LogonUser(
username,
None, # we uses UPN format for username
password,
win32security.LOGON32_LOGON_NETWORK,
win32security.LOGON32_PROVIDER_DEFAULT,
)
folder_name = shell.SHGetFolderPath(0, shellcon.CSIDL_PROFILE, token, 0)
This is why I ended up with this code...which is far from being perfect due to the fact that it requires username and password.
token = win32security.LogonUser(
username,
None, # Here should be the domain ... or just go with default values
password,
win32security.LOGON32_LOGON_NETWORK,
win32security.LOGON32_PROVIDER_DEFAULT,
)
win32security.ImpersonateLoggedOnUser(token)
folder_name = shell.SHGetFolderPath(0, shellcon.CSIDL_PROFILE, 0, 0)
win32security.RevertToSelf()
This question is somehow related: How to find the real user home directory using python?
you could go the win32api.GetUserName() (current user only) or win32net.NetUserGetInfo() (any user on any server, localhost included) route. the latter could be a bit slow since it can take some time to get this information back from the OS.
import win32net
def userDir(username):
return win32net.NetUserGetInfo(None, username, 1).get("home_dir")
alternatively you could expand the environment variable USERPROFILE on windows or HOME on unix to get the information about the currently logged in user:
def userDir():
if os.platform.system() == 'Windows':
return os.environ['USERPROFILE']
elif os.platform.system() == 'Linux':
return os.environ['HOME']
else:
return None
This seems to be only applicable to the current user, but on my (winxp) machine, os.path.expanduser('~') returns my home directory.