unix - run a command as another user [closed] unix - run a command as another user [closed] unix unix

unix - run a command as another user [closed]


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/expectset password "megapassword"spawn /bin/sudo -u user1 /usr/local/bin/script.shexpect "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 pexpectpassword = "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


Either add a NOPASSWD option in /etc/sudoers as Igor says, or just schedule the command in user2's crontab in the first place.