W8_struct_socket_hmac_socketserver

W8_struct_socket_hmac_socketserver

149.struct模块解决黏包问题

cat tcp_server.py

#server 下发命令给客户端执行
import socket,struct

sk = socket.socket()

sk.bind(("127.0.0.1", 8989))
sk.listen()
conn,add = sk.accept()
while True:
    cmd = str(input("CMD:")).strip()
    conn.send(cmd.encode("utf-8"))
    if cmd == 'q':
        break
    ret = conn.recv(4)
    len_num = struct.unpack("i", ret)
    res = conn.recv(len_num[0])
    print(res)

conn.close()
sk.close()

cat tcp_client.py

sk = socket.socket()
sk.connect(("127.0.0.1", 8989))
while True:
    cmd = sk.recv(1024)
    if cmd.decode("utf-8") == 'q':
        break
    res = subprocess.Popen(cmd,shell=True,
                            stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE)
    std_out = res.stdout.read()
    std_err = res.stderr.read()
    len_num = len(std_out) + len(std_err)
    ret = struct.pack("i", len_num)
    sk.send(ret)
    sk.send(std_out)
    # print(std_out)
    sk.send(std_err)
    # print(std_err)
sk.close()

返回顶部

152.struct模块定制报头ftp实践

ftp_server.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import socket
import struct
import json
import hashlib
import sys

def processBar(num, total):
    rate = float(num) / float(total)
    rate_num = int(rate * 100)
    if rate_num == 100:
        r = '\r%s>%d%%\n' % ('=' * rate_num, rate_num,)
    else:
        r = '\r%s>%d%%' % ('=' * rate_num, rate_num,)
    sys.stdout.write(r)
    sys.stdout.flush()



buffer_size = 1024
sk = socket.socket()
sk.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sk.bind(("127.0.0.1", 2121))
sk.listen(5)

conn, add = sk.accept()
ret = conn.recv(4)
header_len = struct.unpack("i", ret)[0]
header = conn.recv(header_len)
header = json.loads(header)
filesize = header["filesize"]
filename = header["filename"]
print(filename, filesize)
recv_size = 0
with open(filename, "wb") as f:
    m = hashlib.md5()
    while recv_size < filesize:
        content = conn.recv(buffer_size)
        m.update(content)
        f.write(content)
        recv_size += len(content)
        #print("got:%s %%" % round(float(recv_size) / float(filesize) * 100, 2))
        processBar(recv_size, filesize)
    md5 = m.hexdigest()
    print(md5)
client_md5 = conn.recv(len(md5))
if md5 == client_md5:
    print("md5 一致")
else:
    print("md5不一致")
# conn.send(b"test")
conn.close()
sk.close()

ftp_client.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-

# @author: Wu
# @date:18-8-28

import socket, json, struct
from os import path as os_path
import hashlib

import sys

upload_file = '/home/wu/Downloads/ubuntu-16.04.4-desktop-amd64.iso'

header = {}

def processBar(num, total):
    rate = float(num) / float(total)
    rate_num = int(rate * 100)
    if rate_num == 100:
        r = '\r%s>%d%%\n' % ('=' * rate_num, rate_num,)
    else:
        r = '\r%s>%d%%' % ('=' * rate_num, rate_num,)
    sys.stdout.write(r)
    sys.stdout.flush()


buffer_size = 1024

header["filesize"] = os_path.getsize(upload_file)
header["filepath"] = os_path.dirname(upload_file)
header["filename"] = os_path.basename(upload_file)
file_size = header["filesize"]

print(header)

json_header = json.dumps(header)

sk = socket.socket()
sk.connect(("127.0.0.1", 2121))
sk.send(struct.pack("i", len(json_header)))
sk.send(json_header)
with open(upload_file, "rb") as f:
    m = hashlib.md5()
    while file_size:
        if file_size >= buffer_size:
            content = f.read(buffer_size)
            m.update(content)
            sk.send(content)
            file_size = file_size - buffer_size

        else:
            content = f.read(file_size)
            m.update(content)
            sk.send(content)
            break
        # percent_num = (float(header["filesize"]) - file_size)/float(header["filesize"])*100
        processBar(header["filesize"] - file_size, header["filesize"])
    print(m.hexdigest())
sk.sendall(m.hexdigest())
# data = sk.recv(1024)
print("done")
sk.close()

https://www.cnblogs.com/Eva-J/articles/8244551.html#_label8

返回顶部

155.hmac的检验客户端合法性

hmac_app_server.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-


import socket
import hmac
from os import urandom

buf_size = 1024
secret_key = "test key"


def handler_server(ip, port):
    sk = socket.socket()
    sk.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sk.bind((ip, port))
    sk.listen(5)
    conn, addr = sk.accept()

    return conn, addr
    # data = conn.recv(buf_size)
    # print(data)
    #
    # conn.send(msg)


def handler_conn(conn):
    pass


def conn_auth(conn):
    random_key = urandom(32)
    conn.sendall(random_key)
    h = hmac.new(secret_key, random_key)
    digest = h.digest()
    res = conn.recv(len(digest))
    return True if res == digest else False


if __name__ == "__main__":
    conn, (ip, port) = handler_server('127.0.0.1', 9999)
    result = conn_auth(conn)
    if result:
        print("client %s:%d 合法:" % (ip, port))
    else:
        print("client %s:%d非法:" % (ip, port))

hmac_app_server.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-


import socket
import hmac
import struct

secret_key = "test key"


def conn_auth(ip, port):
    sk = socket.socket()
    sk.connect((ip, port))
    # ret = sk.recv(4)[0]
    # len_num = struct.unpack("i", ret)
    random_key = sk.recv(32)
    h = hmac.new(secret_key, random_key)
    digest = h.digest()
    res = sk.sendall(digest)
    print(res)


if __name__ == "__main__":
    conn_auth("127.0.0.1", 9999)

返回顶部

156.socketserver模块

#!/usr/bin/env python
# -*- coding: utf-8 -*-


import socketserver


class Myserver(socketserver.BaseRequestHandler):
    def handle(self):
        self.data = self.request.recv(1024).strip()
        print("{} wrote:".format(self.client_address[0]))
        print(self.data)
        self.request.sendall(self.data.upper())


if __name__ == "__main__":
    HOST, PORT = "127.0.0.1", 9999

    # 设置allow_reuse_address允许服务器重用地址
    socketserver.TCPServer.allow_reuse_address = True
    # 创建一个server, 将服务地址绑定到127.0.0.1:9999
    #server = socketserver.TCPServer((HOST, PORT), Myserver)
    server = socketserver.ThreadingTCPServer((HOST, PORT), Myserver)
    # 让server永远运行下去,除非强制停止程序
    server.serve_forever()

返回顶部

解读python中SocketServer源码

refer:http://www.cnblogs.com/Eva-J/p/5081851.html

实践ftp需求


refer:https://www.cnblogs.com/Eva-J/articles/7642557.html

返回顶部

setblocking方法设置非阻塞

import socket

sk = socket.socket()
sk.setblocking(False)
sk.bind(("127.0.0.1",9999))
sk.listen()
try:
    conn,addr = sk.accept()
except BlockingIOError:
    print("catched BlockingIOError")
print("++done++")

返回顶部

posted @ 2018-08-25 23:05  rootid  阅读(156)  评论(0编辑  收藏  举报