Python: Implementing a simple SSH

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.