【发布时间】:2014-05-07 04:44:26
【问题描述】:
我正在从 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>"
【问题讨论】:
-
从您的 pexpect 代码中捕获并显示所有异常。可能是您的 ssh 会话没有作为 apache www-data 用户工作。例如,它通常没有 ~/.ssh/* 文件。
-
我正在执行此脚本,只需将其保存在 /var/www/cgi-bin 文件夹中即可。将其称为 localhost/cgi-bin/test1.py 普通 cgi“来自脚本的格式错误的标头。未定义错误的标头 = 名称“孩子”:test1.py”,在 error_log 中可以看到孩子是生成会话的处理程序
-
你能编辑你的帖子并粘贴你的脚本代码吗?
-
这是一个系统问题 - 您已经超过了所有程序的最大 ptys。 /proc/sys/kernel/pty/nr 是当前分配,/proc/sys/kernel/pty/max 是最大值。您可以通过
ls /dev/pts和lsof /dev/pts/one-of-the-numbers了解谁在使用它们。可能是您的程序的旧版本已挂起。如果他们还在那里,就杀掉他们。并为您的生成调用添加超时pexpect.spawn('ssh -t admin@192.***.***.*** login root', timeout=30) -
哎哟。听起来这是一个锁定的系统...也许您无权创建任何 pty,这意味着您不能使用 pexpect。如果您不需要交互式会话,请尝试使用 python paramiko 模块及其 exec_command 方法。
标签: python linux apache pexpect