将输出从python服务器发送回客户端

时间:2009-06-11 14:12:25

标签: python sockets

我现在有一个小的java脚本服务器正常工作,由:

调用
<?php
  $handle = fsockopen("udp://78.129.148.16",12345);
  fwrite($handle,"vzctlrestart110");
  fclose($handle);
?>

在远程服务器上,以下python服务器正在运行并执行命令的

#!/usr/bin/python
import os
import socket
print "  Loading Bindings..."
settings = {}
line = 0
for each in open('/root/actions.txt', 'r'):
 line = line + 1
 each = each.rstrip()
 if each != "":
   if each[0] != '#':
     a = each.partition(':')
     if a[2]:
       settings[a[0]] = a[2]
     else:
       print "    Err @ line",line,":",each
print "  Starting Server...",
port = 12345
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(("", port))
print "OK."
print "  Listening on port:", port
while True:
    datagram = s.recv(1024)
    if not datagram:
        break
    print "Rx Cmd:", datagram
    if settings.has_key(datagram):
      print "Launch:", settings[datagram]
      os.system(settings[datagram]+" &")
s.close()

是否可以轻松发送命令的输出,当服务器启动并运行命令时输出显示在ssh窗口中,但是我希望将此输出发送回原始浏览器客户端,可能将浏览器设置为等待15秒,然后检查通过套接字接收的任何数据。

我知道我要求的很多,但是我正在创建一个PHP脚本,我对它有很多了解,但是我的python知识缺乏很多。

谢谢, 阿什利

2 个答案:

答案 0 :(得分:1)

是的,您可以读取命令的输出。为此,我建议使用Python subprocess模块。然后你可以s.write()回来。

当然这有一些影响,你可能不得不让你的PHP脚本运行一段时间,因为这个过程可能运行缓慢。

# The pipe behaves like a file object in Python.
process = Popen(cmd, shell=True, stdout=PIPE)
process_output = ""
while process.poll():
     process_output += process.stdout.read(256)
s.write(process_output)

# Better yet.
process = Popen(cmd, shell=true, stdout=PIPE)
stdout, stderr = process.communicate() # will read and wait for process to end.
s.write(stdout)

集成到您的代码中:

# ... snip ...
import subprocess
con, addr = s.accept()
while True:
    datagram = con.recv(1024)
    if not datagram:
        break
    print "Rx Cmd:", datagram
    if settings.has_key(datagram):
        print "Launch:", settings[datagram]
        process = subprocess.Popen(settings[datagram]+" &", shell=True, stdout=subprocess.PIPE)
        stdout, stderr = process.communicate()
        con.send(stdout)
    con.close()
s.close()

答案 1 :(得分:0)

以下是如何获取命令输出的示例:

>>> import commands
>>> s =  commands.getoutput("ls *")
>>> s
'client.py'