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改一下文件格式然后保存就可以了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM