由于经常需要到服务器上执行些命令,有些命令懒得敲,就准备写点脚本直接浏览器调用就好了,比如这样:
因为线上有现成的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改一下文件格式然后保存就可以了。