[英]Run script as another user on Linux
我正在嘗試通過一個簡單的腳本創建一個 Linux 終端菜單。 在腳本中,它將有一些命令,可以在沒有密碼提示的情況下以另一個用戶身份提交作業(例如 shell 腳本)。
我能夠找到以下帖子並且這有效。 如何在沒有密碼的情況下以另一個用戶身份運行腳本但是,有一個方面的影響。 看來用戶可以在該用戶文件夾中運行我不想要的其他腳本。
歡迎任何建議/幫助。
為此。 這是我所擁有的:
用戶名temp1
,這是將運行菜單的用戶。 uid=1001(temp1)、gid=1001(temp1)、groups=1001(temp1)
用戶名wayne
,這是腳本必須提交的用戶才能運行作業 uid=1000(wayne), gid=1000(wayne),groups=1000(wayne),4(adm),24(cdrom),27 (須藤),30(浸)...
腳本script1.sh
, script2.sh
歸wayne
。
-rwxr-xr-x script1.sh -rwxr-xr-x script2.sh
如果我嘗試以temp1
用戶身份訪問/home/wayne
, temp1
被拒絕(預期)
我將腳本設置為 chmod 700 for wayne
。 所以從技術上講,除了wayne
之外,沒有人可以運行它們。
我編輯了 sudo 文件並有以下條目:
temp1 ALL(wayne) NOPASSWD: /home/wayne/script1.sh
當我運行命令su -c "/home/wayne/script1.sh" -s /bin/sh wayne
,腳本運行(如預期的那樣)
當我運行命令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.