nginx本身不支持直接调用shell脚本,我们可以通过安装fastcgi程序,让nginx把调用shell的http请求交给fastcgi程序去处理,然后nginx 再将结果返回给用户方式间接调用shell,这里我们推荐安装fcgiwrap这个通用的 fastcgi 进程管理器来帮助nginx 处理shell程序
一、安装fcgiwrap
# 安装 epel 源 yum -y install epel-release # 安装 fcgi 依赖 yum -y install fcgi fcgi-devel # 安装 fcgiwrap wget https://github.com/gnosek/fcgiwrap/archive/master.zip unzip master.zip cd fcgiwrap-master autoreconf -i ./configure make make install
通过执行以上命令将会把fcgiwrap安装到/usr/local/sbin/fcgiwrap这个路径
二、安装spawn-fcgi
通过安装spawn-fcgi方便启动fcgiwrap程序
#安装spawn-fcgi
yum install spawn-fcgi
修改/etc/sysconfig/spawn-fcgi配置文件
vi /etc/sysconfig/spawn-fcgi
修改配置文件为以下内容
# You must set some working options before the "spawn-fcgi" service will work. # If SOCKET points to a file, then this file is cleaned up by the init script. # # See spawn-fcgi(1) for all possible options. # # Example : #SOCKET=/var/run/php-fcgi.sock #OPTIONS="-u apache -g apache -s $SOCKET -S -M 0600 -C 32 -F 1 -P /var/run/spawn-fcgi.pid -- /usr/bin/php-cgi" FCGI_SOCKET=/var/run/fcgiwrap.socket FCGI_PROGRAM=/usr/local/sbin/fcgiwrap FCGI_USER=nobody FCGI_GROUP=nobody FCGI_EXTRA_OPTIONS="-M 0700" OPTIONS="-u $FCGI_USER -g $FCGI_GROUP -s $FCGI_SOCKET -S $FCGI_EXTRA_OPTIONS -F 1 -P /var/run/spawn-fcgi.pid -- $FCGI_PROGRAM"
添加spawn-fcgi开机启动服务
chkconfig --levels 235 spawn-fcgi on
启动spawn-fcgi服务
/etc/init.d/spawn-fcgi start
三、配置nginx执行shell调用
修改nginx配置文件
vi /usr/local/nginx/conf/nginx.conf
增加以下内容
location ~ ^/.*\.sh { gzip off; root /home/shell; #shell文件存放目录 fastcgi_pass unix:/var/run/fcgiwrap.socket; include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; }
四、创建shell文件
vi /home/shell/hello.sh
添加以下内容
#!/bin/bash echo "Content-Type:text/html" echo "" echo "hello world!"
添加shell脚本执行权限
chmod -R 755 /home/shell
然后在浏览器中输入http://<ip>:port/hello.sh
即可调用我们的shell脚本
说明:
1、脚本前三行是必须的,第一行用于指定脚本执行使用的解释器,第二行和第三行是HTTP协议规范,在发送HTML正文之前要发送MIME头和空行
2、shell脚本都是使用nobody用户执行的,所以要确保nobody可以读取并执行hello.sh
参考文档:https://www.howtoforge.com/serving-cgi-scripts-with-nginx-on-centos-6.0-p2
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?