簡體   English   中英

如何在 vps 中遠程執行 bash 腳本

[英]how to execute bash script inside vps remotely

我的任務是讓第二個開發人員能夠重新啟動 gunicorn 服務,而無需讓他訪問整個虛擬機,他可以通過 ftp 在他的項目目錄中上傳他的項目文件,但他不能自己重新啟動 gunicorn。

我的“script.sh”是:

sudo service gunicorn restart

腳本

我可以用這個命令在終端自己執行 script.sh,它工作正常:
./script.sh

我怎樣才能遠程執行這個腳本? 也許通過 url? 或者如果有其他更好的方法來完成這個任務,請分享

謝謝!

我最喜歡你的兩個想法,一個是編寫一個檢測特定目錄中上傳文件的服務

基本上是一個腳本:

inotifywait /the/dir -m -e CREATE,CLOSE | while read -f action file; do 
      rm "$file"
      systemctl restart that_thing
done

可能對特定文件名和/或密碼檢查進行一些過濾,例如文件名的內容必須是一些密碼。

如果您不使用 Linux,而不是 inotifywait,您可以每秒左右輪詢文件是否存在。

man inotifywaithttps://mywiki.wooledge.org/BashFAQ/001 + https://mywiki.wooledge.org/BashGuide 我懷疑您的服務器使用 rc-scripts,現在是 2021 年,考慮遷移到 systemd。 https://www.linode.com/docs/guides/introduction-to-systemctl/ + https://www.shubhamdipt.com/blog/how-to-create-a-systemd-service-in-linux/

其次是給開發人員訪問權限,他只能觸發特定的命令

設置 ssh 服務器,給開發者一個用戶帳戶,安裝sudo然后在/etc/sudoers.d/other_developer中創建一個文件,內容為:

otherdeveoperuseraccount ALL=(root) NOPASSWD: /usr/bin/systemctl restart that_service

然后其他開發人員將能夠運行該特定命令。

請參閱man sudoman sudoershttps://unix.stackexchange.com/questions/279125/allow-user-to-run-a-command-with-arguments-which-contains-spaces 總的來說,關於如何設置 ssh 服務器和添加用戶帳戶,感興趣的對 Linux 計算機管理的一些基本介紹 - 網上肯定有無窮無盡的。

單程:

  1. 創建一個具有最小權限的用戶。 (不幸的是,一些 shell 特權是必需的)。
  2. 覆蓋 此用戶在 ssh 上強制運行The ONLY command
# 1. Create a user with shell = /bin/sh & no home-dir
sudo adduser limiteduser --shell=/bin/sh --no-create-home

# 2. Restrict further in sshd_config
nano /etc/ssh/sshd_config

## > Add the following at the end
Match user limiteduser
  ForceCommand /path/to/restart-script
  # ForceCommand ls    # Tried this for testing.

PS:一些副作用包括limiteduser用戶訪問隧道端口。 由於用戶已經擁有 FTP 訪問權限; 我假設安全要求不是非常嚴格。


另一種方式 - 因為 FTP 訪問是存在的。

  • 當用戶完成 FTP 上傳后,請他在以下位置創建文件: /path/to/ftp/folder/request-restart.txt
  • [Per-minute]編寫一個 cron 作業來檢查該文件並運行重啟腳本並刪除該文件。
    • @kamilkuk 答案中的 inotify 腳本是一個更好的實時版本。 使用 cron,最大分辨率為 1 分鍾。
  • 這可以擴展為用戶提供更多request-some-other-command
# cron-watch-n-restart-script.sh
FILE="/path/to/ftp/folder/request-restart.txt"
if [[ -f "$FILE" ]]; then
    /path/to/restart-script.sh
    rm $FILE
fi

# Cron job entry (crontab -e): every minute
* * * * * /path/to/cron-watch-n-restart-script.sh

暫無
暫無

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

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