Linux : create a user if not exists

Chris Rebert clp2 at rebertia.com
Tue Aug 16 10:04:11 CEST 2011


On Tue, Aug 16, 2011 at 12:45 AM, smain kahlouch <smainklh at gmail.com> wrote:
> Hi all,
>
> I'm learning the python language and i'm trying to create a user if it is
> not found in the system.
> I figured it out by doing the following thing :
>
>>>> def finduser(user):
> ...     for line in open('/etc/passwd'):
> ...             if line.startswith(user):
> ...                     print user, "user exists"
> ...                     return True
> ...     return False
<snip>
> But i think it's a dirty way to do so. Is there another way to manage users
> with python ?

You can replace the /etc/passwd parsing with a call to pwd.getpwnam():
http://docs.python.org/library/pwd.html#pwd.getpwnam

Cheers,
Chris



More information about the Python-list mailing list