繁体   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