python中使用socket模块验证用户名密码的用例

· Special

python中使用socket模块验证用户名密码的用例

server版本

#运行程序接收标语,校验用户名密码,并发送判断对错(csv版本)
import socket
import json

#对象化
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(('127.0.0.1', 9999))
server.listen(5)



while True:
#创建配对
    conn,adr = server.accept()

    #发送标语
    conn.sendall('欢迎使用用户登录系统'.encode('utf-8'))

    while True:
        #接收客户端数据
        name_pwd = conn.recv(1024).decode('utf-8')

        #处理接收数据
        name_pwd = name_pwd.split('-')
        name = name_pwd[0]
        pwd = name_pwd[1]
        print(f'当前信息为{name}-{pwd},来自ip地址{adr}')



        #打开循环csv文件
        dbdb = open('db.csv','r',encoding='utf-8')

        have_user_pwd = False
        for i in dbdb:
            #分割
            db_user,db_pwd = i.strip().split(',')
            if db_user == name and db_pwd == pwd:
                have_user_pwd = True


        #判断数据是否在数据库,并发送判断结果
        if not have_user_pwd:
            send_judge_info = {'status':False,'msg':'用户名不存在或者密码错误'}
            send_judge_info = json.dumps(send_judge_info)
            conn.sendall(send_judge_info.encode('utf-8'))

        elif have_user_pwd:
            send_judge_info = {'status': True, 'msg': '登录成功'}
            send_judge_info = json.dumps(send_judge_info)
            conn.sendall(send_judge_info.encode('utf-8'))
            break


    conn.close()

client

#接收标语,输入用户名密码,发送用户名密码,接收判断对错(csv版本)

import socket
import json

#对象化
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)


#配对
client.connect(('127.0.0.1', 9999))

#接收展示标语
data_title =client.recv(1024)
print(data_title.decode())

while True:
    #采集用户信息
    user_input_name = input('请输入用户名: ').strip()
    user_input_pwd = input('请输入密码: ').strip()

    #处理采集数据
    send_data = f'{user_input_name}-{user_input_pwd}'

    #发送采集后的数据
    client.sendall(send_data.encode())

    #接收判断
    server_judge = client.recv(1024).decode('utf-8')
    save_judge_info = json.loads(server_judge)
    if save_judge_info.get('status'):
        print(save_judge_info.get('msg'))
        break
    if not save_judge_info.get('status'):
        print(save_judge_info.get('msg'))


client.close()


python


评论

行为验证™ 安全组件加载中...