从Apache httpd运行pexpect
我正在用Python生成一个HTML页面。代码里还有一部分是用pexpect来开启SSH会话并获取命令输出。但是当我从Apache httpd服务器运行Python时,出现了500内部服务器错误
。不过单独执行Python代码是没问题的。
我不确定问题出在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 admin@192.***.***.*** 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>"
1 个回答
0
这个“child”变量是在第一个尝试块(try block)里面定义的。当它离开了这个尝试块的范围后,解释器就不知道这个变量了。你可以通过把所有的尝试块合并成一个来解决这个问题,这样就够了。
试试这个代码片段:
#!/usr/bin/env python
import pexpect
import sys
import time
import cgi, cgitb
import getpass
output = ""
try:
child = pexpect.spawn('ssh -t admin@192.***.***.*** 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>"