Python server / client remote execute problem [duplicate]
I'm working on a project in Python that I'm having trouble with. I've asked so many people but they seem to not be able to help me :/ I'm coding a little program that executes system commands. The idea is that one machine opens the server and the other one opens the client and connects to the IP / Port. From there they can execute system commands and obtain the output. Only problem is, whenever I run the server it opens successfully then when I open the client and connect to the server I get the shell but when I type a command it just hangs until the server is closed then I get the output of the command on the client.
Server.py:
import sys, os, socket
host = ''
port = 50105
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
print("Server started on port: ", port)
s.listen(1)
while (1):
conn, addr = s.accept()
print 'New connection from ', addr
try:
while True:
rc = conn.recv(2)
pipe = os.popen(rc)
rl = pipe.readlines()
fl = conn.makefile('w')
fl.writelines(rl[:-1])
fl.close()
except IOError:
conn.close()
Client.py:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host =开发者_运维问答 'localhost'
port = input('Port: ')
s.connect((host, port))
while (1):
cmd = raw_input('$ ')
s.send(cmd)
file = s.makefile('r', 0)
sys.stdout.writelines(file.readlines())
sys.stdout.flush()
file.close()
I told you exactly what the problem was in this answer to your previous question:
Python - Server and client problems
I'm not joking or anything, I tried your code, I figured out what the problem was, and I told you how to fix it.
Once again, with emphasis:
When you makefile() on the socket and then use readlines() on it, readlines() will continue to read lines until you reach an end of file, which in the socket case when it is closed from the other end. Therefore you do not get any output until the connection is closed, as readlines() will not stop reading lines until the connection is closed.
Neither readlines() nor makefile() in this case makes no sense to me, especially since you create it and close it after each command. Just use send() and recv() on both ends.
You probably also want to have some sort of actual "protocol" so the server tells the client "HERE COMES A RESPONSE" and "THIS IS THE END OF THE RESPONSE" so that the client knows. Otherwise it gets hard to know when to stop waiting for more response. :)
精彩评论