Linux : create a user if not exists
Alexander Kapps
alex.kapps at web.de
Tue Aug 16 11:56:37 EDT 2011
On 16.08.2011 16:57, smain kahlouch wrote:
> Ok than you. You're right but it doesn't help me :
> I replaced it :
>
> >>> def finduser(user):
> ... if pwd.getpwnam(user):
> ... print user, "user exists"
> ... return True
> ... return False
> ...
> >>> finduser('realuser')
> realuser user exists
> True
> >>> finduser('blabla')
> Traceback (most recent call last):
> File "<stdin>", line 1, in ?
> File "<stdin>", line 2, in finduser
> KeyError: 'getpwnam(): name not found: blabla'
Untested:
def finduser(name):
try:
return pwd.getpwnam(name)
except KeyError:
return None
if not finduser("myuser"):
print "creating user..."
else:
print "user already exists"
Has the advantage that finduser() returns the user details if needed.
(BTW: Please don't top-post)
More information about the Python-list
mailing list