gpt4 book ai didi

python - ls-l 执行 popen 时出现问题

转载 作者:太空宇宙 更新时间:2023-11-04 03:53:45 25 4
gpt4 key购买 nike

我的远程 shell 工作得不太好。当我运行命令 ls -l 时,得到了很好的结果,但是当我运行以下命令时,ls -l 再次运行。我不知道我的哪一个是错误的。我使用linux和python 2.7

服务器.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()

客户端.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

最佳答案

一些评论:

  • 除非必要,否则不要使用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()

关于python - ls-l 执行 popen 时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25465681/

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