簡體   English   中英

在 Linux 上以另一個用戶身份運行腳本

[英]Run script as another user on Linux

我正在嘗試通過一個簡單的腳本創建一個 Linux 終端菜單。 在腳本中,它將有一些命令,可以在沒有密碼提示的情況下以另一個用戶身份提交作業(例如 shell 腳本)。

我能夠找到以下帖子並且這有效。 如何在沒有密碼的情況下以另一個用戶身份運行腳本但是,有一個方面的影響。 看來用戶可以在該用戶文件夾中運行我不想要的其他腳本。

歡迎任何建議/幫助。

為此。 這是我所擁有的:

  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 (須藤),30(浸)...

  3. 腳本script1.shscript2.shwayne

     -rwxr-xr-x script1.sh -rwxr-xr-x script2.sh
  4. 如果我嘗試以temp1用戶身份訪問/home/waynetemp1被拒絕(預期)

  5. 我將腳本設置為 chmod 700 for wayne 所以從技術上講,除了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 ,腳本會運行(不是預期的)。

有任何想法嗎?

答案是從 su 更改為 sudo。

su主要用於切換用戶,而sudo用於以其他用戶身份執行命令。 -u標志允許您指定執行命令的用戶為:

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

Sorry user is not allowed to execute

解決方案:為了在 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.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM