First, the service side
1 ImportSocket2 Importsubprocess3 4Phone =Socket.socket (socket.af_inet, socket. SOCK_STREAM)5Phone.setsockopt (socket. Sol_socket, SOCKET. SO_REUSEADDR, 1)6Phone.bind (('127.0.0.1', 8081))#0-65535:0-1024 for operating system use7Phone.listen (5)8 9 Print('starting ...')Ten whileTrue:#Link Loops Oneconn, client_addr =phone.accept () A Print(CLIENT_ADDR) - - whileTrue:#Communication Cycle the Try: - #1. Receiving orders -cmd = CONN.RECV (1024) - if notCmd:#for Linux operating systems + Break - Print('client-side data', cmd) + A #2, execute the order, get the result atobj = subprocess. Popen (Cmd.decode ('Utf-8'), shell=True, -stdout=subprocess. PIPE, -Stderr=subprocess. PIPE) - -stdout =Obj.stdout.read () -stderr =Obj.stderr.read () in #3. Return the result of the command to the client -Conn.send (stdout+stderr) to + exceptConnectionreseterror:#for Windows operating systems - Break the * conn.close () $ Panax NotoginsengPhone.close ()
Second, the client
1 ImportSocket2 Importsubprocess3 4Phone =Socket.socket (socket.af_inet, socket. SOCK_STREAM)5Phone.setsockopt (socket. Sol_socket, SOCKET. SO_REUSEADDR, 1)6Phone.bind (('127.0.0.1', 8081))#0-65535:0-1024 for operating system use7Phone.listen (5)8 9 Print('starting ...')Ten whileTrue:#Link Loops Oneconn, client_addr =phone.accept () A Print(CLIENT_ADDR) - - whileTrue:#Communication Cycle the Try: - #1. Receiving orders -cmd = CONN.RECV (1024) - if notCmd:#for Linux operating systems + Break - Print('client-side data', cmd) + A #2, execute the order, get the result atobj = subprocess. Popen (Cmd.decode ('Utf-8'), shell=True, -stdout=subprocess. PIPE, -Stderr=subprocess. PIPE) - -stdout =Obj.stdout.read () -stderr =Obj.stderr.read () in #3. Return the result of the command to the client -Conn.send (stdout+stderr) to + exceptConnectionreseterror:#for Windows operating systems - Break the * conn.close () $ Panax NotoginsengPhone.close ()
Run Dir on the client and the result is:
1C:\Users\xu516\PycharmProjects\Python Full Stack development \venv\scripts\python.exe"C:/users/xu516/pycharmprojects/python Full Stack development/third module/network programming/04 Analog SSH Remote execution command/client. PY"2>>:d ir3 the volume in drive C is the OS4The serial number of the volume is 7849-BAF95 6C:\Users\xu516\PycharmProjects\Python full stack development \ Third module \ Network Programming \04directory to simulate SSH remote execution commands7 82018/04/06 13:07 <DIR> .92018/04/06 13:07 <DIR> ..Ten2018/04/05 21:18 0__init__. PY One2018/04/06 13:07 376client. PY A2018/04/06 13:06 1,146service side. PY -2018/04/06 11:56 722Add. py -4 Files 2,244bytes the2 Listings 36,491,399,168Available Bytes - ->>:
Server Run Results:
1 starting ... 2 ('127.0.0.1', 62806)3 client data b'dir'
python--Network Programming-----Socket Programming Example--Analog SSH Remote execution command