在Linux上以其他用户身份运行脚本

dzjeubhm  于 2023-05-06  发布在  Linux
关注(0)|答案(3)|浏览(271)

我试图通过一个简单的脚本创建一个Linux终端菜单。在脚本中,它将包含一些命令,这些命令将以另一个用户的身份提交作业(例如shell脚本),而无需密码提示。
我找到了下面的帖子,这起作用了。**how to run script as another user without password**不过有一个附带的影响。看来用户可以运行其他脚本在该用户文件夹中,我不希望。
欢迎任何建议/帮助。
为了这个。这是我的:
1.用户名temp1,将运行菜单的用户。uid=1001(temp1),gid=1001(temp1),groups=1001(temp1)
1.用户名wayne,这是脚本必须作为其提交以运行作业的用户uid=1000(wayne),gid=1000(wayne),groups=1000(wayne),4(adm),24(cdrom),27(sudo),30(dip)...
1.脚本script1.shscript2.shwayne拥有。

-rwxr-xr-x script1.sh
-rwxr-xr-x script2.sh

1.如果我尝试以temp1用户的身份访问/home/wayne,则权限被拒绝(预期)
1.我将wayne的脚本设置为chmod 700。所以从技术上讲,除了wayne之外,没有人可以运行它们。
1.我已经编辑了sudo文件,并有以下条目:

temp1 ALL(wayne) NOPASSWD: /home/wayne/script1.sh

1.当我运行命令su -c "/home/wayne/script1.sh" -s /bin/sh wayne时,脚本运行(如预期)
1.当我运行命令su -c "/home/wayne/script2.sh" -s /bin/sh wayne时,脚本运行(不期望)。
有什么想法吗

1aaf6o9v

1aaf6o9v1#

答案是从su变成sudo。
su主要用于切换用户,而sudo用于作为其他用户执行命令。-u标志允许您指定以哪个用户的身份执行命令:

sudo -u wayne '/home/wayne/script2.sh'

给出Sorry user is not allowed to execute

nimxete2

nimxete22#

解决方案:为了在linux/unix上以另一个用户的身份运行命令/脚本,你需要sudo权限并运行以下公式:

sudo -H -u <user> bash -c '<some-command>'

例如示例

sudo -H -u wayne bash -c 'echo "user:$USER|home:$HOME|action:run_script"; ./home/wayne/script.sh'

来自文档

sudo allows a permitted user to execute a command as the superuser or
 another user, as specified by the security policy.
 
-H   The -H (HOME) option requests that the security policy set
     the HOME environment variable to the home directory of the
     target user (root by default) as specified by the password
     database.  Depending on the policy, this may be the default
     behavior.

-u    user The -u (user) option causes sudo to run the specified
      command as a user other than root.  To specify a uid
      instead of a user name, use #uid.  When running commands as
      a uid, many shells require that the '#' be escaped with a
      backslash ('\').  Security policies may restrict uids to
      those listed in the password database.  The sudoers policy
      allows uids that are not in the password database as long
      as the targetpw option is not set.  Other security policies
      may not support this.
vaj7vani

vaj7vani3#

不要忽略“runuser”。我发现这正是我在/etc/cron.hourly中运行Python脚本所需要的

相关问题