unix - 以另一个用户身份运行命令 [英] unix - run a command as another user

查看:34
本文介绍了unix - 以另一个用户身份运行命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Unix 的新手.我正在尝试以另一个用户身份运行 shell 脚本和命令.

I am a newbie to Unix. I am trying to run a shell script and command as another user.

例如:我以 user1 身份登录并希望以 user2 身份执行脚本.我不想要密码提示,我希望它是自动输入的.我知道公钥认证,但我试图找出是否有类似的东西:

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

我正在尝试 cron 这个,所以我不想要密码提示.我希望它在 sudo 命令本身中处理.

I am trying to cron this, so I dont want the password prompt. I want it to be handled in the sudo command itself.

请帮忙

推荐答案

您可以在 /etc/sudoers 文件中添加 NOPASSWD 选项.但出于安全原因,这可能对您不利.

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

您拥有的另一个选项:使用 sudo,但不是直接从某个脚本运行它,而是使用 pexpectexpect,这将为您输入密码.从安全角度来看,这也可能不太理想,因为您需要在脚本中保存密码.

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.

使用 expect,您可以执行以下操作:

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

不要忘记为该文件设置 500 权限.

Don't forget to set 500 permission on that file.

使用 pexpect(即一个 python 模块),它看起来像:

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)

如果你在 cron 中运行命令并且可以将命令添加到 user1 的 crontab 中,你也可以这样做.这可能是最好的解决方案.

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

这篇关于unix - 以另一个用户身份运行命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆