简体   繁体   中英

Running pexpect from apache httpd

I am generating HTML page from Python. There is also logic for spawning a SSH session using pexpect and fetching command output inside same Python code. But when I run Python from Apache httpd server, it is giving me 500 internal server error . But executing Python code separately is working fine.

Not sure if issue is in Python or Apache?

Code is below and I have added the exception for debugging purpose. Exception shows

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>"

The child variable is defined in the scope of the first try block. When it goes out of the scope of the first try block it becomes unknown to the interpreter. You could fix this by merging all your try blocks into one. Which is enough.

Try with this snippet:

#!/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>"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM