python - 执行popen的ls-l问题

时间:2014-08-23 19:33:36

标签: python linux

我有一个无法正常工作的远程shell。当我运行命令时,ls -l给我带来了一个好结果,但是当我运行以下命令时,ls -l再次运行。我不知道哪一个是我的错误。 我使用linux和python 2.7

server.py

import socket, shlex
import subprocess

PORT = 9999
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(('',PORT))
sock.listen(4)

sc, addr = sock.accept()

while True:
    comando = sc.recv(255)
    if comando == 'exit':
        break   
    else:
        print comando
        if " " in comando:
            comando = shlex.split(comando)
            shell = subprocess.Popen(comando,bufsize=255, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)

        else:
            shell = subprocess.Popen(comando, shell=True, bufsize=255,stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)
        stdout, stderr = shell.communicate()
        if not stdout:
            stdout = shell.stderr.read()
        if len(stdout) == 0:
            stdout = "[Comando ejecutado]"

    sc.send(stdout)

sc.close()
sock.close()

client.py

import socket, sys, os
s = socket.socket()
s.connect(("localhost", 9999))

mensaje = ""
while mensaje != "exit":
    mensaje = raw_input("Shell# ")
    try:
        s.send(mensaje)
        resultado = s.recv(2048)
        print resultado 
    except:
        print "Hubo un error en la conexion..."
        mensaje = "exit"          

print "bye..."

s.close()

我猜错误是popen和childs

1 个答案:

答案 0 :(得分:0)

一些评论:

  • 除非必须

  • ,否则请勿使用shell=True
  • subprocess.check_output()是运行命令的最简单方法,检查命令是否失败,并获取输出

  • 发生错误时,打印出状态代码以帮助追踪正在发生的事情。有时命令没有被正确解析,即文件名中的空格。

import socket, shlex
import subprocess

PORT = 9999
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(('',PORT))
sock.listen(5)

sc, addr = sock.accept()

while True:
    comando = sc.recv(255).rstrip()
    print 'got:',comando
    if not comando:
        break
    elif comando == 'exit':
        break   

    comando = shlex.split(comando)
    print comando
    output = 'ERROR'
    try:
        output = subprocess.check_output(
            comando,
            stdin=subprocess.PIPE, 
            stderr=subprocess.PIPE, 
            shell=False,
            )
    except subprocess.CalledProcessError as err:
        output = "[Comando ejecutado] status={}".format(err.returncode)
    sc.send(output)

sc.close()
sock.close()