在Linux上以另一个用户身份运行脚本

时间:2014-11-22 18:19:00

标签: linux bash shell

我正在尝试通过简单的脚本创建Linux终端菜单。在脚本中,它将有一些命令将作为另一个没有密码提示的用户提交作业(例如shell脚本)。

我能找到以下帖子,这很有效。的 how to run script as another user without password 但是,有一个副作用。用户可以在该用户文件夹中运行我不想要的其他脚本。

任何建议/帮助欢迎。

为此。这就是我所拥有的:

  1. 用户名temp1,即运行菜单的用户。 uid = 1001(temp1),gid = 1001(temp1),groups = 1001(temp1)

  2. 用户名wayne,用户必须提交脚本才能运行作业 uid = 1000(wayne),gid = 1000(wayne),groups = 1000(wayne),4(adm),24(cdrom),27(sudo),30(dip)......

  3. script1.sh所拥有的脚本script2.shwayne

    -rwxr-xr-x script1.sh
    -rwxr-xr-x script2.sh
    
  4. 如果我尝试以/home/wayne temp1用户身份转到wayne,我会被拒绝(预期)

  5. 我将脚本设置为chmod 700 for wayne。所以从技术上讲,除了temp1 ALL(wayne) NOPASSWD: /home/wayne/script1.sh 以外,没有人可以运行它们。

  6. 我编辑了sudo文件并输入以下内容:

    su -c "/home/wayne/script1.sh" -s /bin/sh wayne
  7. 当我运行命令su -c "/home/wayne/script2.sh" -s /bin/sh wayne时,脚本会运行(如预期的那样)

  8. 当我运行命令{{1}}时,脚本会运行(不是预期的)。

  9. 有什么想法吗?

2 个答案:

答案 0 :(得分:6)

答案是从su变为sudo。

su主要用于切换用户,而sudo用于执行其他用户的命令。 -u标志允许您指定执行命令的用户: sudo -u wayne' /home/wayne/script2.sh'给对不起用户不允许执行

答案 1 :(得分:0)

解决方案:为了在 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.