PDA

View Full Version : Python server/client remote execution question



breaksand30
01-25-2011, 05:59 AM
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, with the output, I get something like this:


Enter a command: ls
got: ls
received: 2
Enter a command:

I want the output of the command, and everything I try to add doesn't work.

Server.py:


import sys, socket

#socket.setdefaulttimeout(150)

host = ''
port = 50103
BUFSIZE = 1024

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
print("Server started on port: %s"%port)
s.listen(1)
print("Now listening...\n")

#conn = client socket


conn, addr = s.accept()

while True:
print 'New connection from %s:%d' % (addr[0], addr[1])
data = conn.recv(BUFSIZE)
if not data:
break
elif data == 'exit':
conn.send('\0')
else:
conn.send(data)


def quit(connection):
connection.close()


Client.py:


import sys
import socket

BUFSIZE = 1024

conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
conn.connect(('localhost', 50103))
while True:
cmd = raw_input('Enter a command: ')
conn.send(cmd)
data = conn.recv(BUFSIZE)
msglen = len(data)
print "got: %s" % data
print "received: %d" % msglen
if data == '\0':
print 'exiting...'
sys.exit(0)

Kakao
01-25-2011, 10:27 AM
You only coded the communication part. There is no code on the server to execute the command. Look at the subprocess module to achieve the execution of commands.