【问题标题】:Run script as another user on Linux在 Linux 上以另一个用户身份运行脚本
【发布时间】:2014-11-22 18:18:59
【问题描述】:

我正在尝试通过一个简单的脚本来创建一个 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.shscript2.shwayne 所有。

    -rwxr-xr-x script1.sh
    -rwxr-xr-x script2.sh
    
  4. 如果我尝试以 temp1 用户的身份访问 /home/wayne,我的权限被拒绝(预期)

  5. 我将 wayne 的脚本设置为 chmod 700。所以从技术上讲,除了wayne,没有人可以运行它们。

  6. 我已经编辑了 sudo 文件并有以下条目:

    temp1 ALL(wayne) NOPASSWD: /home/wayne/script1.sh
    
  7. 当我运行命令 su -c "/home/wayne/script1.sh" -s /bin/sh wayne 时,脚本运行(如预期)

  8. 当我运行命令 su -c "/home/wayne/script2.sh" -s /bin/sh wayne 时,脚本运行(不是预期的)。

有什么想法吗?

【问题讨论】:

  • 您的示例问题和您的问题之间的一个区别是另一个问题使用user1 ALL=(user2) NOPASSWD: /home/user2/bin/test.sh,但您在您的版本中省略了=。那可能就是错的。它可能是无辜的。值得一试。
  • 我确保它具有相同的结果并且仍然得到相同的结果。输出归韦恩所有,所以我知道它运行正确的脚本。

标签: linux bash shell


【解决方案1】:

答案是从 su 改为 sudo。

su主要用于切换用户,sudo用于以其他用户身份执行命令。 -u 标志可让您指定执行命令的用户为:

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

Sorry user is not allowed to execute

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-30
      • 2019-01-22
      • 2015-07-10
      • 2011-02-18
      相关资源
      最近更新 更多