unix - run a command as another user [closed]

心不动则不痛 提交于 2020-01-30 04:57:09

问题


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


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/11105444/unix-run-a-command-as-another-user

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!