Change user on UNIX

Jonathan Gardner jgardner at jonathangardner.net
Thu Mar 20 10:46:25 EDT 2008


On Mar 20, 4:51 am, "Giampaolo Rodola'" <gne... at gmail.com> wrote:
> Hi all.
> Is there any way to su or login as a different user within a python
> script? I mainly need to temporarily impersonate another user to
> execute a command and then come back to the original user.
> I tried to google a little bit about it but I still didn't find a
> solution.

In the unix world, this is highly discouraged. You shouldn't have to
change your user. The only user who can change roles---and who should
change roles for security reasons---is root.

The only reason sudo is around is for those people who really are root
but who don't like logging in as root to do root work. With a very
limited permission set for sudo, it is very, very easy to get full
root access.

  $ sudo cp /bin/cp /bin/cp.old; sudo cp /bin/su /bin/cp; sudo cp -
  #

If you want a different user to access files that another user
created, that's what groups are for. You should create a common group
and then share the files by assigning them to that group and setting
the appropriate permissions. Yes, this is painful, and every once in a
while you get files that don't have the right permissions or the group
is set to the wrong group. But this is the cost of running on a system
where multiple users can be doing things all at once, and the cost of
trying to make sure that users can't hurt each other. Someone
somewhere has to say, "You are allowed to do this much, but no more".

If that's not what you need, then you need to run the process as root.
It can change its user and even chroot to a jail if need be. This is
how apache, for instance, works. It starts as root and spawns the
server processes as the apache user.

(Apache does have an interesting problem with home directories, and it
has a very special solution that is very insecure. Even there, the
better solution is to put all the user's files under a common group in
a common folder outside of their home directories.)



More information about the Python-list mailing list