2014-03-27 110 views
0

我正在從Python生成HTML頁面。 也有用於在相同的Python代碼中使用pexpect和fetching命令輸出產生SSH會話的邏輯。但是當我從Apache httpd服務器運行Python時,它給了我500 internal server error。 但分開執行Python代碼工作正常。從apache httpd運行pexpect

不確定問題出在Python還是Apache?

代碼在下面,我爲調試目的添加了異常。 異常顯示

Exception seen in Web page : 
Error! pty.fork() failed: out of pty devices name 
'child' is not defined name 
'child' is not defined name 
'child' is not defined name 
'child' is not defined name 
'child' is not defined name 
'child' is not defined name 
'child' is not defined name 

Code is below ############################################################# 

import pexpect 
import sys 
import time 
import cgi, cgitb 
import getpass 
print "Content-Type: text/html\n\n" 

try: 
     child = pexpect.spawn('ssh -t [email protected]***.***.*** login root') 
except Exception, e: 
     print e 
try: 
     child.expect('(?i)password') 
except Exception, e: 
     print e 
try: 
     child.sendline('password') 
except Exception, e: 
     print e 
try: 
     child.expect('(?i)Password:') 
except Exception, e: 
     print e 
try: 
     child.sendline('password') 
except Exception, e: 
     print e 
try: 
     child.expect('-bash# ') 
except Exception, e: 
     print e 
try: 
     child.sendline('ls -al') 
except Exception, e: 
     print e 
try: 
     child.expect('-bash# ') 
except Exception, e: 
     print e 
output = child.before 
print "Content-Type: text/html\n\n" 
print "<html>" 
print "<head>" 
print "<title>Hello </title>" 
print "</head>" 
print "<body>" 
print "<h1>",output,"</h1>" 
print "</body>" 
print "</html>" 
+0

捕捉並顯示您的Pexpect的代碼的所有異常。這可能是你的ssh會話不能用作apache www-data用戶。例如,它通常沒有〜/ .ssh/*文件。 – tdelaney

+0

我正在通過將它保存在/ var/www/cgi-bin文件夾中來執行此腳本。調用它爲localhost/cgi-bin/test1.py plain cgi 「來自腳本的格式不正確的頭文件錯誤的頭文件= name'child'未定義:test1.py」,在error_log中顯示child是會話產生的處理程序 – NoviceInPython

+0

你能編輯你的文章並粘貼你的腳本代碼? – ylabidi

回答

0

子變量在第一個try塊的範圍內定義。當它超出第一個嘗試塊的範圍時,解釋者就不知道了。你可以通過將你所有的try塊合併成一個來解決這個問題。這就夠了。

嘗試用這個片段:

#!/usr/bin/env python 

import pexpect 
import sys 
import time 
import cgi, cgitb 
import getpass 


output = "" 
try: 
     child = pexpect.spawn('ssh -t [email protected]***.***.*** login root') 
     child.expect('(?i)password') 
     child.sendline('password') 
     child.expect('(?i)Password:') 
     child.sendline('password') 
     child.expect('-bash# ') 
     child.sendline('ls -al') 
     child.expect('-bash# ') 
     output = child.before 
except Exception, e: 
    print e 

print "Content-Type: text/html\n\n" 
print "<html>" 
print "<head>" 
print "<title>Hello </title>" 
print "</head>" 
print "<body>" 
print "<h1>",output,"</h1>" 
print "</body>" 
print "</html>" 
+0

謝謝你! 是的,我曾嘗試以上述方式,它仍然說 **「Error!pty.fork()失敗:出pty設備」** – NoviceInPython

+0

看看[this](http:// stackoverflow。 COM /問題/ 8561121 /故障排除-OSERROR-OUT-OF-PTY的設備)。它可能會幫助你。 – ylabidi

+0

謝謝!爲您提供幫助。我試過那個頁面沒用。 – NoviceInPython