从apache httpd运行pexpect

时间:2014-03-27 22:35:57

标签: python linux apache pexpect

我正在从Python生成HTML页面。 还有一些逻辑用于在相同的Python代码中使用pexpect和fetching命令输出生成SSH会话。但是当我从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>"

1 个答案:

答案 0 :(得分: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 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>"