title: Python sending command over a socket
body: <p>I'm having a bit of trouble. I want to create a simple program that connects to the server and executes a command using subprocess then returns the result to the client. It's simple but I can't get it to work. Right now this is what I have:
  client:</p>
  
  <pre><code>
  import sys, socket, subprocess
  conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  host = sys.argv[1]
  port = int(sys.argv[2])
  socksize = 1024
  conn.connect((host, port))
  while True:
      shell = raw_input("$ ")
      conn.send(shell)
      data = conn.recv(socksize)
      #msglen = len(data)
      output = data
      iotype = subprocess.PIPE
      cmd = ['/bin/sh', '-c', shell]
      proc = subprocess.Popen(cmd, stdout=iotype).wait()
      stdout,stderr = proc.communicate()
      conn.send(stdout)
      print(output)
      if proc.returncode != 0:
          print("Error")
  </code></pre>
  
  <p>server:</p>
  
  <pre><code>
  import sys, socket, subprocess
  host = ''               
  port = 50106
  socksize = 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, addr = s.accept()
  while True:
      print 'New connection from %s:%d' % (addr[0], addr[1])
      data = conn.recv(socksize)
      cmd = ['/bin/sh', '-c', data]
      proc = subprocess.Popen(cmd, stdout=subprocess.PIPE).wait()
      stdout,stderr = cmd.communicate()
      if not data:
          break
      elif data == 'killsrv':
          sys.exit()
  </code></pre>