socket

Posted navy2013

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了socket相关的知识,希望对你有一定的参考价值。

 

1.通过socket实现简单的ssh

技术分享图片
import socket,os
server=socket.socket()
server.bind(("localhost",9999))
server.listen()

while True:
    print("等待新指令")
    conn,addr=server.accept()
    print("new conn:",addr)
    while True:
        data=conn.recv(1024)
        if not data:
            print("客户端已断开")
            break
        print("执行命令:",data)
        cmd_res=os.popen(data.decode("utf-8").read()  #接收字符串,执行结果也是字符串
        print("before send",len(cmd_res)
        if len(cmd_res)==0:
            cmd_res="cmd has not output..."
        conn.send(cmd_res.encode("utf-8"))
        print("send done")
server.close()
socket_server_ssh

 

技术分享图片
import socket
client=socket.socket()
client.connect(("localhost,9999"))

while True:
    cmd=input(">>:").strip()
    if len(cmd)==0:continue
    client.send(cmd.encode("utf-8")
    cmd_res=client.recv(1024)
    print(cmd_res.decode())
    
client.close()
socket_client_ssh

 

2.通过socket接收大数据

技术分享图片
import socket,os
server=socket.socket()
server.bind(("localhost",9999))
server.listen()

while True:
    print("等待新指令")
    conn,addr=server.accept()
    print("new conn:",addr)
    while True:
        data=conn.recv(1024)
        if not data:
            print("客户端已断开")
            break
        print("执行命令:",data)
        cmd_res=os.popen(data.decode("utf-8").read()  #接收字符串,执行结果也是字符串
        print("before send",len(cmd_res)
        if len(cmd_res)==0:
            cmd_res="cmd has not output..."
        conn.send(str(len(cmd_res.encode()).encode("utf-8")   #len(cmd_res)整数不能encode,需转化成字符串再encode;先发大小给客户端
        conn.send(cmd_res.encode("utf-8"))
        print("send done")
server.close()
socket_server_data

 

技术分享图片
import socket
client=socket.socket()
client.connect(("localhost,9999"))

while True:
    cmd=input(">>:").strip()
    if len(cmd)==0:continue
    client.send(cmd.encode("utf-8")
    cmd_res_size=client.recv(1024)   #接收命令结果的长度
    print("命令结果大小:",cmd_res_size)
    cmd_res=client.recv(1024)
    print(cmd_res.decode())
    
client.close()
socket_client_data

 

进阶版

 

技术分享图片
import socket,os,time
server=socket.socket()
server.bind(("localhost",9999))
server.listen()

while True:
    
    conn,addr=server.accept()
    print("new conn:",addr)
    while True:
    print("等待新指令")
        data=conn.recv(1024)
        if not data:
            print("客户端已断开")
            break
        print("执行命令:",data)
        cmd_res=os.popen(data.decode("utf-8").read()  #接收字符串,执行结果也是字符串
        print("before send",len(cmd_res)
        if len(cmd_res)==0:
            cmd_res="cmd has not output..."
        conn.send(str(len(cmd_res.encode())).encode("utf-8") )  #len(cmd_res)整数不能encode,需转化成字符串再encode;先发大小给客户端
        #time.sleep(0.5)      #2条send紧挨着在linux会粘包,防粘包
        client_ack=conn.recv(1024)  #wait client to confirm
        print("ack from client:",client_ack)
         conn.send(cmd_res.encode("utf-8"))     
        print("send done")
server.close()
socket_server_data1

 

技术分享图片
import socket
client=socket.socket()
client.connect(("localhost,9999"))

while True:
    cmd=input(">>:").strip()
    if len(cmd)==0:continue
    client.send(cmd.encode("utf-8")
    cmd_res_size=client.recv(1024)   #接收命令结果的长度
    print("命令结果大小:",cmd_res_size)
    client.send("准备好接收了,loser可以发了".encode("utf-8"))
    received_size=0
    received_data=b‘‘
    while received_size<int(cmd_res_size.decode()):
    data=client.recv(1024)
    received_size+=len(data) #每次收到的有可能小于1024,所以必须用len判断
    print(data.decode())
    received_data+=data
    
    else:
        print("cmd res receive done...",received_size)
        print(received_data.decode())
        
client.close()
    
client.close()
socket_client_data1

 

3.通过socket实现文件传送

技术分享图片
import socket,hashlib

server=socket.socket()
server.bind(("localhost,9999"))
server.listen()

while True:
    conn,addr=server.accept()
    print("new conn:",addr)
    while True:
        print("等待新指令")
        data=conn.recv(1024)
        if not data:
            print("客户端已断开")
            break
            
        cmd,filename=data.decode().split()
        print(filename)
        if os.path.isfile(filename):
            f=open(filename,"rb")
            m=hashlib.md5()
            file_size=os.stat(filename).st_size
            conn.send(str(file_size).encode())  #send file size
            conn.recv(1024)   #wait for ack
            for line in f:
                m.update(line)
                conn.send(line)
            print("file md5",m.hexdigest())
            f.close()
            
        print("send done")
server.close()
ftp_socket_server

 

技术分享图片
import socket
client=socket.socket()
client.connect(("localhost,9999"))

while True:
    cmd=input(">>:").strip()
    if len(cmd)==0:continue
    if cmd.startswith("get"):
        client.send(cmd.encode())
        server_response=client.recv(1024)
        print("server response:",server_response)
        client.send(b"ready to recv file)
        file_total_size=int(server_response.decode())
        received_size=0
        filename_cmd.split()[1]
        f=open(filename,"wb)
        while received_size<file_total_size:
            data=client.recv(1024)
            received_size+=len(data)
            f.write()
            #print(file_total_size,received_size)
        else:
            print("file recv done",received_size,file_total_size)
            f.close()
            
        
client.close()
ftp_socket_client

 

除了传送文件,还要添加MD5

技术分享图片
import socket,hashlib

server=socket.socket()
server.bind(("localhost,9999"))
server.listen()

while True:
    conn,addr=server.accept()
    print("new conn:",addr)
    while True:
        print("等待新指令")
        data=conn.recv(1024)
        if not data:
            print("客户端已断开")
            break
            
        cmd,filename=data.decode().split()
        print(filename)
        if os.path.isfile(filename):
            f=open(filename,"rb")
            m=hashlib.md5()
            file_size=os.stat(filename).st_size
            conn.send(str(file_size).encode())  #send file size
            conn.recv(1024)   #wait for ack
            for line in f:
                m.update(line)
                conn.send(line)
            print("file md5",m.hexdigest())
            f.close()
            conn.send(m.hexdigest().encode())   #send md5
            
        print("send done")
server.close()
ftp_socket_server_md5

 

技术分享图片
import socket,hashlib
client=socket.socket()
client.connect(("localhost,9999"))

while True:
    cmd=input(">>:").strip()
    if len(cmd)==0:continue
    if cmd.startswith("get"):
        client.send(cmd.encode())
        server_response=client.recv(1024)
        print("server response:",server_response)
        client.send(b"ready to recv file)
        file_total_size=int(server_response.decode())
        received_size=0
        filename_cmd.split()[1]
        f=open(filename,"wb)
        m=hashlib.md5()
        while received_size<file_total_size:
            if file_total_size-received_size>1024:  #要收不止一次
                size=1024
                
            else:  #最后一次了,剩多少收多少
                size=file_total_size-received_size
            data=client.recv(size)
            received_size+=len(data)
            m.update()
            f.write(data)
            #print(file_total_size,received_size)
        else:
            new_file_md5=m.hexdigest()
            print("file recv done",received_size,file_total_size)
            f.close()
        server_file_md5=client.recv(1024)
        print("server file md5:",server_file_md5)
        print("client file md5:",new_file_md5)
            
        
client.close()
ftp_socket_client_md5

 

4. SocketServer

技术分享图片
import socketserver

class MyTCPHandler(socketserver.BaseRequestHandler):
    
    def handler(self):
        while True:
            try:
                self.data=self.request.recv(1024).strip()
                print("{} wrote:".format(self.client_address[0]))
                print(self.data)
                #if not self.data:
                    #print(self.client_address,"断开了")
                    #break
                self.request.sendall(self.data.upper())
            except ConnectionResetError as e:
                print("客户端断开了")
                break
    if __name__="__main__":
        HOST,PORT="localhost",9999
        server=socketserver.TCPServer((HOST,PORT),MyTCPHandler)
        server.serve_forever()
socketserver_server

 

技术分享图片
import socket

client=socket.socket()
client.connect(("localhost",9999))

while True:
    msg=input(">>:").strip()
    if len(msg)==0:continue
    client.send(msg.encode("uft-8")
    data=client.recv(1024)
    print("recv:",data.decode())
    
client.close()
socketserver_client

 

以上是关于socket的主要内容,如果未能解决你的问题,请参考以下文章

Python干货socket中的listen()参数(数字)到底代表什么?

paper 78:sniff抓包程序片段

通过 c# 与 socket.io 服务器通信

微信小程序代码片段

VSCode自定义代码片段——CSS选择器

谷歌浏览器调试jsp 引入代码片段,如何调试代码片段中的js