socket_server_ssh.py
#!usr/bin/env python
#-*-Coding:utf-8-*-
__author__ = "Samson"
Import socket
Import OS
Server = Socket.socket (socket.af_inet,socket. SOCK_STREAM)
Server.bind (("localhost", 6969))
Server.listen ()
While True:
CONN,ADDR = Server.accept ()
Print ("New conn:", addr)
While True:
data = CONN.RECV (1024)
If not data:
Print ("Client disconnected!")
Break
Print ("Execute command:", data)
Cmd_res = Os.popen (Data.decode ()). Read ()
If Len (cmd_res) = = 0:
Print ("Command has no output")
Conn.send (str (Cmd_res.encode ())). Encode ("Utf-8")) #连续两条send可能会出现粘包, it is recommended to recv immediately after send
Conn.send (Cmd_res.encode ("Utf-8"))
Server.close ()
socket_server_client.py
#!usr/bin/env python
#-*-Coding:utf-8-*-
__author__ = "Samson"
Import socket
Client = Socket.socket ()
Client.connect (("localhost", 6969))
While True:
cmd = input (">>:"). Strip ()
If Len (cmd) = = 0:
Continue
Client.send (Cmd.encode ("Utf-8"))
Cmd_res_size = Client.recv (1024x768) #接受命令结果的长度
Print ("Command result size:", cmd_res_size)
Received_size = 0
While received_size < int (Cmd_res_size.decode ()):
data = CLIENT.RECV (1024)
Received_size + = len (data) #接收到的数据可能小于1024
Print (Data.decode ())
Else
Print ("cmd res receive done!")
Client.close ()
Python: Implementing a simple SSH