• python--socket实例


    模拟SSH--client:

    # Author:Tim Gu
    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(1024)
        client.send(b"start_trans")
        sev_file_size = int(cmd_res_size.decode())
        #print('sev_file_size',sev_file_size,type(sev_file_size))
        received_size = 0
        received_data = b''
    
        while received_size < sev_file_size:
            data = client.recv(1024)
            #print("收到数据!")
            received_size += len(data)
            received_data += data
            #print('cli_file_size',received_data)
        else:
            #print("receive done...",received_size)
            print(received_data.decode())
    
    client.close()
    

     模拟SSH--server:

    # Author:Tim Gu
    
    import socket,os,time
    server = socket.socket()
    server.bind(('localhost',6969))
    
    server.listen()
    
    while True:
        print("beging waiting request...")
        conn,addr = server.accept()
        print("new conn:",addr)
        while True:
            print("request comming!",addr)
            data = conn.recv(1024)
            if not data:
                print("客户端已断开")
                break
            print("执行指令:",data)
            cmd = data.decode()
            cmd_res = os.popen(cmd).read()
            print("before send",len(cmd_res.encode('utf-8')))
            if len(cmd_res) == 0:
                com_res = "cmd has no output..."
            conn.send(str(len(cmd_res.encode('utf-8'))).encode('utf-8'))
            #time.sleep(0.5)
            client_ack = conn.recv(1024) #wait client confirm
            conn.send(cmd_res.encode("utf-8"))
            print("send done")
    server.close()
    

    socketserver简易server:

    # Author:Tim Gu
    import socket
    import socketserver
    
    class MyTCPHandler(socketserver.BaseRequestHandler):
        def handle(self):
            while True:
                try:
                    print("开始监听!")
                    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.send(self.data.upper())
                except (WindowsError,ConnectionRefusedError) as e:
                    print(e)
                    break
    
    
    if __name__ == "__main__":
        HOST,PORT="localhost",9999
        server = socketserver.ThreadingTCPServer((HOST,PORT),MyTCPHandler)
        server.serve_forever()
    

     socketserver简易client:

    # Author:Tim Gu
    import socket
    def myquit():
        choose = input("是否退出?'y' or 'n':").strip()
        if choose == 'y':
            exit("退出!")
        else:
            pass
    
    
    client = socket.socket()
    client.connect(('localhost',9999))
    
    while True:
        msg = input(">>").strip()
        if len(msg) == 0:continue
        client.send(msg.encode('utf-8'))
        data = client.recv(10240)
        print("recv:",data.decode())
        myquit()
    client.close()
    

    传文件server:

    # Author:Tim Gu
    
    import socket,os,time,hashlib
    server = socket.socket()
    server.bind(('localhost',6969))
    
    server.listen()
    
    while True:
        print("beging waiting request...")
        conn,addr = server.accept()
        print("new conn:",addr)
        while True:
            print("request comming!",addr)
            data = conn.recv(1024)
            if not data:
                print("客户端已断开")
                break
            cmd,filename = data.decode().split()
            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('utf-8')) #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())
    
    
            print("send done")
    server.close()
    

    传文件client:

    # Author:Tim Gu
    import socket,hashlib
    client = socket.socket()
    client.connect(('localhost',6969))
    
    while True:
        cmd = input(">>").strip()
        if len(cmd) == 0:continue
        if cmd.startswith('get'):
            client.send(cmd.encode('utf-8'))
            server_response = client.recv(1024)
            print('server response:',server_response)
            client.send(b'start to trans')
            file_total_size = int(server_response.decode())
            received_size = 0
            file_name = cmd.split()[1]
            f = open(file_name+".new",'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(data)
                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()
    

    本周作业:

    client:

    import socket
    import os,json
    import hashlib
    
    
    
    class FtpClient(object):
        def __init__(self):
            self.client = socket.socket()
    
        def cmd_help(self,args):
            msg = '''
            ls
            pwd
            cd
            get filename
            put filename
            '''
            print(msg)
    
        def connect(self,ip,port):
            self.client.connect((ip,port))
    
        def interactive(self):
            self.auth()
            while True:
                cmd = input(">>").strip()
                if len(cmd) == 0:continue
                cmd_str = cmd.split()[0]
                if hasattr(self,'cmd_%s'%cmd_str):
                    func = getattr(self,'cmd_%s'%cmd_str)
                    func(cmd)
                else:
                    self.help()
    
    
    
        def cmd_put(self,*args):
            cmd_split = args[0].split()
            if len(cmd_split) > 1:
                filename = cmd_split[1]
                os.path.isfile(filename)
                filesize = os.stat(filename).st_size
                msg_dic = {
                    'action': 'put',
                    'filename': filename,
                    'filesize': filesize,
                    'overridden': True
                }
                self.client.send(json.dumps(msg_dic).encode('utf-8'))
                server_response = self.client.recv(1024)
                f = open(filename,'rb')
                m = hashlib.md5()
                for line in f:
                    m.update(line)
                    self.client.send(line)
                else:
                    print("file upload success...")
                f.close()
                self.client.send(m.hexdigest().encode())
                sev_md5_check = self.client.recv(1024)
                print(sev_md5_check.decode())
            else:
                print('file is not exist')
    
        def cmd_get(self):
            pass
    
    
        def auth(self):
            pass
    
    
    
    class Account(object):
        def __init__(self):
            pass
    
    
    
    ftp = FtpClient()
    ftp.connect('localhost',9999)
    ftp.interactive()
    

    server:

    # Author:Tim Gu
    import socket,hashlib
    import socketserver,json,os
    
    class MyTCPHandler(socketserver.BaseRequestHandler):
    
        def put(self,*args):
            cmd_dic = args[0]
            filename = cmd_dic['filename']
            filesize = cmd_dic['filesize']
            if os.path.isfile(filename):
                f = open(filename + ".new",'wb')
            else:
                f = open(filename,'wb')
            self.request.send(b'200,ok')
            recived_size = 0
            m = hashlib.md5()
            while recived_size < filesize:
                data = self.request.recv(1024)
                m.update(data)
                f.write(data)
                recived_size += len(data)
            else:
                f.close()
                print("file [%s] has uploaded..."%filename)
                recived_md5 = m.hexdigest()
                source_md5 = self.request.recv(1024).decode()
                if recived_md5 == source_md5:
                    self.request.send('MD5校验成功'.encode('utf-8'))
                else:
                    self.request.send('MD5校验失败'.encode('utf-8'))
    
    
    
    
    
        def handle(self):
            while True:
                try:
                    print("开始监听!")
                    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
                    cmd_dic = json.loads(self.data.decode())
                    action = cmd_dic['action']
                    if hasattr(self,action):
                        func = getattr(self,action)
                        func(cmd_dic)
    
    
    
    
                except ConnectionRefusedError as e:
                    print(e)
                    break
    
    
    if __name__ == "__main__":
        HOST,PORT="localhost",9999
        server = socketserver.ThreadingTCPServer((HOST,PORT),MyTCPHandler)
        server.serve_forever()
    
  • 相关阅读:
    刷题62—生命游戏
    刷题61—有效括号的嵌套深度
    system.transfer.list深度解析
    recovery 升级界面顶部花屏问题分析
    recovery 升级过程LED灯闪烁
    recovery 差分升级包制作超时
    recovery 升级过程执行自定义shell命令
    recovery log直接输出到串口
    android recovery代码修改之原生建议
    android recovery 升级UI显示之资源文件
  • 原文地址:https://www.cnblogs.com/guqing/p/6399454.html
Copyright © 2020-2023  润新知