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"><br/> AllowOverride None<br/> Options +ExecCGI<br/> Order allow,deny<br/> Allow from all # Options Indexes FollowSymLinks MultiViews +ExecCGI<br/> # AllowOverride None<br/> # Options None<br/> # Order allow,deny<br/> # Allow from all<br/> </Directory>
chmod -R 755 /var/www/cgi-bin/
#!/usr/bin/python<br/> #coding=utf-8 print "Content-type:text/html"<br/> print<br/> print '<html>'<br/> print '<head>'<br/> print '<title>Hello</title>'<br/> print '</head>'<br/> print '<body>' import sys<br/> import subprocess reload(sys)<br/> sys.setdefaultencoding('utf-8')<br/> print subprocess.call(["/bin/grep", "exception", "/var/log/error/20160706.log"])<br/> print "<br>"<br/> result1 = subprocess.Popen(["/bin/grep exception /var/log/error/20160706.log"], shell=True, stdout=subprocess.PIPE)<br/> result = subprocess.Popen(["grep","not"],stdin=result1.stdout, stdout=subprocess.PIPE)<br/> out,err = result.communicate()<br/> print out.encode('utf-8')<br/> print "<br>"<br/> print err print '</body>'<br/> print '</html>'
配置好后,用浏览器访问:
因为之前目录不是在www下,而是/var/www/html/cgi-bin/,于是就怀疑suexec:
然而改成/var/www/cgi-bin/依然不行,而且suexec也并木有错误日志,看Apache的错误日志:
既然有第二句,那找不到文件应该不是aaa.py找不到,于是我直接执行了一下py脚本: