unix - run a command as another user
sudo, unix
Solution
You can add NOPASSWD option to `/etc/sudoers` file. But may be it is not a good for you for security reasons.
user user2 = NOPASSWD: /usr/local/bin/script.sh
Another option that you have: use `sudo`, but run it not directly from some script, but using `pexpect` or `expect`, that will enter the password for you. That is also may be not ideal from security point of view, because you need to save the password in the script.
With `expect` you can do something like:
#!/usr/bin/expect
set password "megapassword"
spawn /bin/sudo -u user1 /usr/local/bin/script.sh
expect "password for user:"
send "$password\r"
expect eof
Don't forget to set 500 permission on that file.
With `pexpect` (that is a python module) this will look like:
import pexpect
password = "megapassword"
p = pexpect.spawn("sudo -u user1 /usr/local/bin/script.sh")
i = p.expect([".ssword:*", pexpect.EOF])
p.sendline(password)
If you run the command in `cron` and can add the command to the crontab of user1, you can do that also. That may be the best solution.
user1$ crontab -e
Problem
I am a newbie to Unix. I am trying to run a shell script and command as another user. For example: I am logged in as user1 and want to execute a script as user2. I dont want the password prompt and I want it to be auto-entered. I am aware of the public key authentication but I am trying to find if there is something like: ``` sudo -u user2 script.sh ``` I am trying to cron this, so I dont want the password prompt. I want it to be handled in the sudo command itself. please help