gpt4 book ai didi

python - 从 apache httpd 运行 pexpect

转载 作者:太空宇宙 更新时间:2023-11-04 04:01:54 24 4
gpt4 key购买 nike

我正在从 Python 生成 HTML 页面。还有使用 pexpect 生成 SSH session 并在同一 Python 代码中获取命令输出的逻辑。但是当我从 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>"

最佳答案

子变量在第一个 try block 的范围内定义。当它超出第一个 try block 的范围时,解释器就无法识别它。您可以通过将所有 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>"

关于python - 从 apache httpd 运行 pexpect,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22700678/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com