【发布时间】:2020-03-27 20:23:36
【问题描述】:
我正在尝试做客户端-服务器项目。在这个项目中,我必须将 linux 命令从客户端发送到服务器。现在我可以发送一些命令,如 ls、pwd 等,它们运行正常,我可以在客户端读取输出,但是当我尝试发送“cd”命令时,我没有收到任何错误,但服务器中的目录没有不改变。如果我使用 os.chdir(os.path.abspath(data)) 命令而不是 subprocess.check_output ,它可以更改目录,但它是无用的,因为我可以发送其他命令,如 ls、pwd、mkdir 等。谢谢你帮助
服务器端:
def threaded(c):
while True:
# data received from client
data = c.recv(1024)
if not data:
print('Bye')
break
try:
data_o = subprocess.check_output(data, shell=True)
except subprocess.CalledProcessError as e:
c.send(b'failed\n')
print(e.output)
if(len(data_o) > 0):
c.send(data_o)
else:
c.send(b'There is no terminal output.')
# connection closed
c.close()
客户端:
while True:
# message sent to server
s.send(message.encode('ascii'))
# messaga received from server
data = s.recv(1024)
# print the received message
print('Received from the server :',str(data.decode('ascii')))
# ask the client whether he wants to continue
ans = input('\nDo you want to continue(y/n) :')
if ans == 'y':
message = input("enter message")
continue
else:
break
# close the connection
s.close()
【问题讨论】:
标签: python linux subprocess client-server