点击(此处)折叠或打开

  1. #socket_server.py

  2. import socket
  3. import os
  4. import sys

  5. def work():
  6.         sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  7.         sock.bind(('0.0.0.0',1000))
  8.         sock.listen(5)
  9.         while True:
  10.                 try:
  11.                         conn, addr = sock.accept()
  12.                         ret = conn.recv(2048)
  13.                         result = os.popen(ret).read()
  14.                         conn.send(result)
  15.                 except KeyboardInterrupt:
  16.                         print 'Now we will exit'
  17.                         sys.exit(0)
  18.         sock.close()

  19. if __name__ == '__main__':
  20.         work()
socket实例化,并且绑定1000端口,持续进行监听,'0.0.0.0'表示监听本地。sock.listen(backlog)表示可同时监听连接的数量,一般为5。sock.accept()返回(connection,address),connection通常用来发送和接收数据,address是客户端的Internet地址。conn.recv(2048)进行接收数据,然后conn.send(result)将结果送回给客户端。

点击(此处)折叠或打开

  1. #socket_client.py

  2. import socket

  3. def socket_send(command):
  4. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  5.         sock.connect(('192.168.1.55', 1000))
  6.         sock.send(command)
  7.         result = sock.recv(2048)
  8.         sock.close()
  9.         return result

  10. if __name__ == '__main__':
  11. print socket_send('ls')
sock.connect(address),里面是一个tuple,IP地址和PORT,发送命令给server,然后用result接收结果并进行return
11-10 07:13