socket模块

实现简单的远程连接:

客户端:



import socket
client = socket.socket()#声明socket类型,同时生成socke连接t对象
client.connect(('localhost',969))  #连接到localhost主机的6969端口上去
while True:
        msg = input(">>:").strip()
        if len(msg) == 0:continue
        client.send(msg.encode('utf-8'))#把编译成utf-8的数据发送出去
        data = client.recv(512)#接收数据
        print("从服务器接收到的数据为:",data.decode())
client.close()



服务器端:



import socket
import os
server = socket.socket()#声明socket类型,并且生成socket连接对象
server.bind(('localhost',969))#把服务器绑定到localhost的6969端口上
server.listen(5)#开始监听
print("等待连接中……")
while True:
        conn,addr = server.accept()#接收连接
        print("***连接成功***")
        while True:
                data = conn.recv(512)#接收客户发来的数据
                print("接收到的命令为:",data)
                if not data:
                        print("客户断开连接")
                        break
                com = os.popen(data.decode()).read()#read()读取内存地址的内容
                print(data.decode())#输出结果为字符串dir
                print(os.popen(data.decode()))#输出结果为一个内存地址
                #py3 里socket发送的只有bytes,os.popen又只能接受str,所以要decode一下
                conn.sendall(com.encode('utf-8'))
server.close()



 

 


 稍微加强了下的远程连接:

客户端:



import socket
client = socket.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)
    received_size = 0#接收到的大小为0
    received_data = b''#接收到的数据内容为空
    #根据接收到的数据大小,循环接受数据使其生成完整的内容再跳出循环
    while received_size < int(cmd_res_size.decode()):
        data = client.recv(1024)
        received_size += len(data)
        received_data += data
    #跳出循环后执行
    else:
        print("cmd res receive done……",received_size)
        print(received_data.decode())

client.close()



服务器端:



import socket ,os
server = socket.socket()#声明socket类型并生产连接对象
server.bind(('localhost',9999))#绑定ip和port
server.listen()#监听
print('等待连接……')
#循环接入
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()).read()#把比特流数据转为str,再执行指令,最后读取到内存赋值给变量cmd_res
        print("before send:",len(cmd_res))
        #判断cmd_res是否为 0,popen函数执行失败返回 0
        if len(cmd_res) == 0:
            cmd_res = "cmd has no output..."
        #cmd_res为字符串,.encode()后变为比特流,再用len计算出比特流的大小,再把这个整数转为字符串,最后转为比特流发送出去
        conn.send( str(len(cmd_res.encode())).encode("utf-8") )
        #把指令执行内容编译成比特流发送出去
        conn.send(cmd_res.encode("utf-8"))
        print("send done")
server.close()



 

 

ftp客户端:



import socket
import 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 + ".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
                                print("last received:",size)

                        data = client.recv(size)
                        received_size += len(data)
                        m.update(data)
                        f.write(data)
                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服务器端:



import socket,os
import hashlib
server = socket.socket()
server.bind(('0.0.0.0',9999))
server.listen(5)
print("等待连接....")
while True:
        conn,addr = server.accept()
        print("连接成功....")
        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() )
                        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("文件发送完毕....")
server.close()



 

 



 

socketserver模块

实现简单的连接:

客户端:



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'))
    data = client.recv(10240)
    print("从服务器接受到的数据:",data.decode())

client.close()



服务器端:



import socketserver
class MyTCPHandler(socketserver.BaseRequestHandler):
    def handle(self):
        while True:
            try:
                self.data = self.request.recv(1024).strip()
                if not self.data:
                    print("客户已断开")
                    break
                print("{} wrote:".format(self.client_address[0]))
                print(self.data)
                self.request.send(self.data.upper())
            except ConnectionResetError as e:
                print("Error:",e)
                break

if __name__ == "__main__":
    HOST,PORT = "localhost",9999
    server = socketserver.TCPServer((HOST,PORT),MyTCPHandler)
    server.serve_forever()