Apache执行Python脚本

由于经常需要到服务器上执行些命令,有些命令懒得敲,就准备写点脚本直接浏览器调用就好了,比如这样:

 因为线上有现成的Apache,就直接放它里面了,当然访问安全要设置,我似乎别的随笔里写了安全问题,这里就不写了。

vim /etc/httpd/conf/httpd.conf
 
LoadModule cgid_module modules/mod_cgid.so
 
AddHandler cgi-script .cgi .py
 
ScriptAlias /cgi-bin/ "/var/www/cgi-bin/"
 
<Directory "/var/www/cgi-bin">
   AllowOverride None
   Options +ExecCGI
   Order allow,deny
   Allow from all
 
#    Options Indexes FollowSymLinks MultiViews +ExecCGI
#    AllowOverride None
#    Options None
#    Order allow,deny
#    Allow from all
</Directory>
chmod -R 755  /var/www/cgi-bin/
#!/usr/bin/python
#coding=utf-8
 
print "Content-type:text/html"
print
print '<html>'
print '<head>'
print '<title>Hello</title>'
print '</head>'
print '<body>'
 
import sys
import subprocess
 
reload(sys)
sys.setdefaultencoding('utf-8')
print subprocess.call(["/bin/grep", "exception", "/var/log/error/20160706.log"])
print "<br>"
result1 = subprocess.Popen(["/bin/grep exception /var/log/error/20160706.log"], shell=True, stdout=subprocess.PIPE)
result = subprocess.Popen(["grep","not"],stdin=result1.stdout, stdout=subprocess.PIPE)
out,err = result.communicate()
print out.encode('utf-8')
print "<br>"
print err
 
print '</body>'
print '</html>'

 配置好后,用浏览器访问:

 因为之前目录不是在www下,而是/var/www/html/cgi-bin/,于是就怀疑suexec:

 然而改成/var/www/cgi-bin/依然不行,而且suexec也并木有错误日志,看Apache的错误日志:

既然有第二句,那找不到文件应该不是aaa.py找不到,于是我直接执行了一下py脚本: 

 这就很明显了,这python后面多了点东西,这明显是编码之类的问题,vim进aaa.py,用:set ff看了一下,原来因为这个脚本是在windows上创建的,所以格式是fileformat=dos,用:set ff=unix改一下文件格式然后保存就可以了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lmr廖

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值