Today, I saw the network programming chapter in python core programming. I tried to use the socket module to write a c/s applet, this program can execute commands on the remote server on the linux client. For example, A and B are two linux Hosts, A is A server, and B is A client, run server. pysocket server), execute client on B. pysocket client), so that the linux Command can be sent to server A through socket on client B, after the command is executed on A, the execution result is returned to B through socket, the following code is used:
Server. py:
#coding:utf-8import osimport socketimport subprocessHOST = '192.168.1.10' PORT = 50008 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)s.bind((HOST, PORT))s.listen(5)while True: conn, addr = s.accept() print 'Connected by', addr while True: command = conn.recv(1024) if not command: break if command == 'quit': break #data = os.popen(command).read() result = subprocess.Popen(command,shell=True,stdout=subprocess.PIPE, stderr=subprocess.STDOUT) data = result.stdout.read() conn.sendall(data) conn.close()s.close()
Client. py:
#coding:utf-8import socketHOST = '192.168.1.10' PORT = 50008 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)s.connect((HOST, PORT))while True: command = raw_input('Input your linux command: ') if command == 'quit': break if not command: break s.send(command) data = s.recv(10240)#.decode('utf-8') if not data: break print datas.close()
If you have any questions, please contact me in time
This article is from the "Halcyon" blog, please be sure to keep this source http://halcyonsky.blog.51cto.com/604918/1290641