Switching users in a bash script

0

I want to execute a bash script that switches user and then executes a series of commands. None of this users have root privileges. I guess I have to edit the sudoers file to give user1 (the user executing the script) privileges to be able to log as user2 with no password prompt. I've been looking for this example but I haven't found any.

Thanks in advance.

eliocs

Posted 2011-03-29T06:48:01.697

Reputation: 113

Answers

1

In this example:

  • User running the script = fred
  • User the script wants to run certain commands as = boris
  • Commands the script wants to run as boris = /bin/cat & /bin/rm

In the sudoers file (visudo) have:

fred   ALL=(boris) NOPASSWD:/bin/cat, (boris) NOPASSWD:/bin/rm

Then in the script:

#!/bin/sh
sudo -u boris cat /home/boris/privatefile
sudo -u boris rm /home/boris/privaterubbish

If you want to allow fred to execute any command as boris use this in sudoers:

fred    ALL=(boris) NOPASSWD:ALL

Majenko

Posted 2011-03-29T06:48:01.697

Reputation: 29 007

You should consider reformatting the second paragraph, e.g. to a list. – Daniel Beck – 2011-03-29T07:52:39.590

This is exactly what I'm looking for! – eliocs – 2011-03-29T10:57:03.590

0

Put the series of commands in a file, make it start with #!/bin/sh, and make it executable. Then give the users permission to run that script with visudo.

Beware: this is likely to provide escapes for them to run any command. An alternative is to write a C program that executes the commands in question. Even then you need to watch your step, e.g. clean the environmentvariables the user could use to smuggle in ways to make your commands execute in ways you haven't anticipated.

reinierpost

Posted 2011-03-29T06:48:01.697

Reputation: 1 904

0

The sudoers file is pretty self documenting in my experience; it's filled with comments and examples. You can get pretty granular with the permissions as @reinierpost mentioned, and you should be aware that you're effectively giving this user superuser permissions by authorizing them to use sudo.

If you're just looking to allow the user to run arbitrary commands you'll likely be adding something like:

origuser           ALL = (ALL) ALL 

or if you want to bypass the password prompt

origuser           ALL = NOPASSWD: ALL

As far as switching users go, you might use sudo -u [command] or sudo -u -i [command] if you need the 'destination' user's environment.

thatothermitch

Posted 2011-03-29T06:48:01.697

Reputation: 101

urk no - that will give origuser *FULL ROOT ACCESS* – Majenko – 2011-03-29T07:52:05.847

you're right; i also noted that in my answer – thatothermitch – 2011-03-29T07:58:20.337

full root access is not desired in my case. – eliocs – 2011-03-29T10:57:31.547