Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a user exists in a GNU/Linux OS using Python?

Tags:

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?

like image 945
Elifarley Avatar asked Mar 29 '10 18:03

Elifarley


People also ask

How do you check to see if a user exists in Linux?

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.

How do I check if a user exists?

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 # ....


1 Answers

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.') 
like image 157
Asclepius Avatar answered Sep 27 '22 16:09

Asclepius