python - get the session user - python

I'm running the same Python script for different users on my PC (Windows 10). This script has to get the user who is actually logged in. For example getpass.getuser() isn't working because it just returns the user for which the Python script is running. How can I get this? Thanks for help!

The whole point of Run as... is to mimic the environment of another user so, naturally, when you query for the username (which essentially gets you the value of %USERNAME% env. variable) you'll get the one under which you're running the script.
To get the currently logged in user, you'll have prod the current session, and to do that, at the very least, you'll have to query WMIC (or access the Win32 API directly). Something like:
import subprocess
def get_session_user():
res = subprocess.check_output(["WMIC", "ComputerSystem", "GET", "UserName"],
universal_newlines=True)
_, username = res.strip().rsplit("\n", 1)
return username.rsplit("\\", 1)
Beware that this will return a tuple containing both the system/domain of the currently logged-in user and the username itself, so call it as:
system, username = get_session_user()
To get both.

Related

Using powershell variables in my python script?

I have made a user creation script in powershell, and I am almost done writing the website automation part of it in python with selenium. My problem lies in the joining of the 2. I would like my Python script to use the new user creds I entered in powershell.
So hopefully the PS script would run fully, but before exiting it starts my python script and uses the creds to build him website profiles as well. I have done quite a bit of research the last couple days and cannot figure this out.
Thank you!
You can solve it with passing them only one time rather than saving passwords clear text. Although, if you enable Powershell logging, check what will end up in those logs.
$user1 = "test1"
$cred1 = "testpass1"
# you can also concatenate if necessary, adding all users/pws with some separators
$user2 = "test2"
$cred2 = "testpass2"
$users=$user1+","+$user2
$creds=$cred1+","+$cred2
PS > py .\path_to\create_web_profiles.py $users $creds # make sure you use _py_ and not python / python3.
create_web_profiles.py:
import sys
users = sys.argv[1]
passwords = sys.argv[2]
def getusers(users, passwords):
users=users.split(",")
passwords=passwords.split(",")
print('Usernames: ',users,'Passwords: ',passwords)
for user,passw in zip(users,passwords):
create_web_user(user,passw)
def create_web_user(user, passw):
# your web functions come here
print(user,passw)
pass
getusers(users, passwords)
Output:
PS > py .\path_to\create_web_profiles.py $users $creds
Usernames: ['test', 'test2'] Passwords: ['tpass', 'tpass2']
test tpass
test2 tpass2

Can't open Microsoft Teams with python (3.8) script using any method

I am trying to make a script to automate the login into Microsoft Teams and all of my code works except the part where the application has to be opened. The weird thing is that this is capable of opening any other application except MS Teams (Chrome, Notepad, Firefox, Edge etc.)
Here's the relevant code:
def openfile():
if os.stat("stor.txt").st_size == 0:
name = filedialog.askopenfilename()
newfile = open("stor.txt", "w")
newfile.write(name)
else:
name = (open("stor.txt", "r").read())
os.startfile(name)
sleep(5)
keyboard.write(open("user.txt", "r").read())
keyboard.press("enter")
sleep(3)
keyboard.write(open("pass.txt", "r").read())
keyboard.press("enter")
I tried this with os.startfile, os.system(start..) and every other method on the web. Doesn't work.
The value I'm passing in to os.startfile() when I try to run Teams is C:/Users/Raghav/AppData/Local/Microsoft/Teams/Update.exe.
First of all, I don't recommend storing your password in plain text like that. It's not very secure, and if another program takes focus at the right time your code will even type your password somewhere else!
Teams should remember your credentials after the first time you log in. I suggest letting it handle that part.
In any case, running os.startfile("foo.exe") is like double-clicking on foo.exe. The file name that you're passing in is C:/Users/Raghav/AppData/Local/Microsoft/Teams/Update.exe, and Update.exe doesn't look like something that should launch Teams to me.
Inspecting the Teams shortcut in my own Start menu, I see that things are a bit more complicated. This shortcut runs Update.exe and passes it some arguments:
C:\...\Update.exe --processStart "Teams.exe"
There is no way to pass arguments to a program with os.startfile(). Try os.system() instead:
os.system('C:/Users/Raghav/AppData/Local/Microsoft/Teams/Update.exe --processStart "Teams.exe"')
There are lots of other ways to run external commands in Python, but this is likely simplest since you don't need Teams' output streams. This command should return 0 if it succeeds and some other value if it fails.
import os
os.system("C:\\Users\\Lenovo\\AppData\\Local\\Discord\\Update.exe --processStart Discord.exe")
For applications that have an address like above, there are also some tips:
Sometimes Discord.exe name of the file in the address have "Discord.exe" (with double-quotes). Remove it.
Instead of single \ use double \\ in the address.
It will definitely work GO AHEAD ✔

User permission for only execute

I have a python script on raspberryi pi 3. I want to make it only executable for x user without having root permission. It can not be readable and writable. How can I do that? I gave only x(execute) permission to the file for x user. But when I execute the script, it wants root password.
If the user has access to the script, he can modify the content himself. However, just for the sake of the answer or method, we can do something like this:
You can restrict the access to the script by getting the username of the person on the operating the system:
import getpass
if getpass.getuser() in ['user1','user2'] # allowed user list:
main() # main function
else:
print("You are not authorised to run this script")

How can i check which user is currently logged in on the computer with python?

So i wonder if there is a way to find out which user is currently logged in on the computer, and store it in a variable so i get print it out or do something else with it later.
The reason why i need this is because when i enter a path including the user, it's gonna be diffrent depending on which user is logged in.
I tried to look for this on the internet but i could't find what I was looking for.
OS: Windows 8.1
Version: Python 3.4
Let me know if there is anything i need to clearify.
OT: I'm sorry for any potential mistakes i've done, i'm new to this site.
Example:
checkuser = #The user currently logged in
print("The user currently logged in is: " + checkuser)
So for example if ExampleUser would be logged in it would print:
"The user currently logged in is: ExampleUser"
Check this site
the answer with your snippet would be:
import getpass
checkuser = getpass.getuser()
print("The user currently logged in is: " + checkuser)
Also if you need the name just because of the home directory path you can use os.environ['HOMEPATH'] (on Windows) to get the path directly.
Use the getpass module. It provides you with a getuser function that will return current user.
https://docs.python.org/2/library/getpass.html
Example:
from getpass import getuser
print(getuser())

How to create an executable that is a service or a normal process?

I created a service based on this code Is it possible to run a Python script as a service in Windows? If possible, how?
But when i run the code I can only run it as a service and not a normal process.
Is it possible to create a script that when it is run by an admin it runs as a service, but when its activated without admin privileges it runs as a normal process?
With win32service (some docs here) you can also get the user info by calling the method GetUserObjectInformation, with differente type parameters to get one of UOI_FLAGS,UOI_NAME, UOI_TYPE, or UOI_USER_SID. The complete list of user info types can be found here.
To have a look just print the info somewhere on your program, like the snippet below. If the user name is all that you need win32api will get you there easier.
print win32api.GetUserName()
print win32service.GetUserObjectInformation( win32service.OpenInputDesktop(0,0,1), 4)
# or simply:
print win32service.GetUserObjectInformation( win32service.GetProcessWindowStation(), 4)
Finally, in order to get the privileges directly you can use win32net like so:
win32net.NetUserGetInfo(None, win32api.GetUserName() , 11 )['priv']
This will return an int which maps to:
win32netcon.USER_PRIV_GUEST (0)
win32netcon.USER_PRIV_USER (1)
win32netcon.USER_PRIV_ADMIN (2)
In your program you can check if win32net.NetUserGetInfo(None, win32api.GetUserName() , 11 )['priv'] == win32netcon.USER_PRIV_ADMIN to launch it as a service or not.
For more information on the extensions you can find a brief reference here.

Categories

Resources