我正在从Python生成HTML页面。还有使用pexpect生成SSH会话并在相同的Python代码中获取命令输出的逻辑。但是当我从Apache httpd服务器运行Python时,它给出了500 internal server error。但是单独执行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>"发布于 2014-03-28 09:14:08
子变量在第一个try块的作用域中定义。当它超出第一个try块的作用域时,解释器就不知道它了。您可以通过将所有try块合并为一个块来修复此问题。这就足够了。
尝试使用以下代码片段:
#!/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>"https://stackoverflow.com/questions/22700678
复制相似问题