What is the easiest way to check the existence of a user on a GNU/Linux OS, using Python?
Anything better than issuing ls ~login-name
and checking the exit code?
And if running under Windows?
user infomation is stored in /etc/passwd, so you can use "grep 'usename' /etc/passwd" to check if the username exist. meanwhile you can use "id" shell command, it will print the user id and group id, if the user does not exist, it will print "no such user" message.
Method #2: Find out if user exists in /etc/passwd file #!/bin/bash # init USERID="$1" #.... /bin/egrep -i "^${USERID}:" /etc/passwd if [ $? -eq 0 ]; then echo "User $USERID exists in /etc/passwd" else echo "User $USERID does not exists in /etc/passwd" fi # ....
This answer builds upon the answer by Brian. It adds the necessary try...except
block.
Check if a user exists:
import pwd
try:
pwd.getpwnam('someusr')
except KeyError:
print('User someusr does not exist.')
Check if a group exists:
import grp
try:
grp.getgrnam('somegrp')
except KeyError:
print('Group somegrp does not exist.')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With