bonjour j'ai reconstruit mon programme de servuer dee chat en python, l'idée principale serait de sotcker les mdp et username de chaque utilisateur dansune BDD en sqlite3 de python et regarde si il est inscrit avant de le laisser se connecter pour cela j'ai utilisé un système de codage (/a, /i …): serveur:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 | import socket import sys import threading import select import sqlite3 # main variables _HOST = '192.168.1.22' _PORT = 4567 _BUFFER = 1024 _RUNNING = True _USERS = [] # colors for different kinds of data BLUE = '\033[94m' GREEN = '\033[92m' RED = '\033[1;31m' PURPLE = '\033[1;34m' print(PURPLE + " █████╗ ██████╗ ██████╗ ███████╗███╗ ██╗ █████╗ ██╗ ██╗███╗ ██╗███████╗ \n" " ██╔══██╗██╔══██╗██╔══██╗██╔════╝████╗ ██║██╔══██╗██║ ██║████╗ ██║╚══███╔╝ \n" " ███████║██║ ██║██████╔╝█████╗ ██╔██╗ ██║███████║██║ ██║██╔██╗ ██║ ███╔╝ \n" " ██╔══██║██║ ██║██╔══██╗██╔══╝ ██║╚██╗██║██╔══██║██║ ██║██║╚██╗██║ ███╔╝ \n" " ██║ ██║██████╔╝██║ ██║███████╗██║ ╚████║██║ ██║███████╗██║██║ ╚████║███████╗ \n" " ╚═╝ ╚═╝╚═════╝ ╚═╝ ╚═╝╚══════╝╚═╝ ╚═══╝╚═╝ ╚═╝╚══════╝╚═╝╚═╝ ╚═══╝╚══════╝ \n" " hammer05 - backtrack05 / v1.0 beta / contact me hammer1.adrenalinz@yahoo.com \n") class Query(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.sql = sqlite3.connect('database.db') self.query = self.sql.cursor() def broadcast_one(self, receiver, lister, data): """ encode and send data to a receiver (used for new_account()) """ for sockb in lister: if sockb == receiver: try: sockb.send(data.encode()) except: sockb.close() lister.remove(sockb) def inscription(self, requester, username, password, lister): """ Used to create a new account in server's database """ self.query.execute('IF NOT EXISTS CREATE TABLE users_data' ' (username TEXT NOT NULL UNIQUE,' ' password TEXT NOT NULL UNIQUE)') try: self.query.execute('INSERT INTO users_data VALUES(?, ?)', (username, password)) self.sql.commit() print(GREEN + '[' + requester + '] created a new account (' + username, password + ')\n') self.broadcast_one(requester, lister, '/op') except sqlite3.IntegrityError: print(RED + 'User[' + requester + '] tried to create a new account: username already token... ERROR SENT\n') self.broadcast_one(requester, lister, '/er') def connect(self, requester, username, password, lister): """ Used to check if users data is already in dataabse and allowing access to server """ account = (username, password) self.query.execute('SELECT * FROM users WHERE username = ? AND password = ?', account) lock = self.query.fetchall() if username in lock and password in lock: print(GREEN + 'User[' + username + '] entered the chat-room') self.broadcast_one(requester, lister, '/at access authorized...') else: print(RED + 'User[' + requester + '] failed log in ERROR SENT\n') self.broadcast_one(requester, lister, RED + '/ad access denied...') Sqlrequests = Query() # instance the class to use it in Server() class Server(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.host = socket.gethostbyname(_HOST) self.port = int(_PORT) self.buffer = _BUFFER self.run = _RUNNING self.users = _USERS self.username = {} self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) def broadcast_data(self, sock, data): """ encode and send data to all connected users except the sender """ for sockt in self.users: if sockt != self.sock and sockt != sock: try: sockt.send(data.encode()) except: sockt.close() self.users.remove(sockt) def broadcast_one(self, receiver, data): """ encode and send data to a receiver (used for new_account()) """ for sockb in self.users: if sockb == receiver: try: sockb.send(data.encode()) except: sockb.close() self.users.remove(sockb) def main(self): """ In this function all others will be assembled as a puzzle to build the server """ try: # binding the server and listening incoming connections self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.sock.bind((self.host, self.port)) self.sock.listen(10) # 10 connections MAX self.users.append(self.sock) except socket.error: print(RED + 'Unable to connect ot the remote host: {0}'.format(self.host)) sys.exit() print(GREEN + 'Chat server started on port: ' + str(self.port) + '\r') while 1: read_sockets, write_sockets, in_error = select.select(self.users, [], []) for sockp in read_sockets: if sockp == self.sock: sockfd, addr = self.sock.accept() self.users.append(sockfd) else: try: data = sockp.recv(self.buffer).decode() if data: spliter = data.split() # for data harvesting and differentiation if '/i' == spliter[0]: # register code new account will be created user = spliter[1] # data harvesting passwd = spliter[2] # data harvesting Sqlrequests.inscription(sockp, user, passwd, self.users) if '/a' == spliter[0]: # connection code call the connect function user = spliter[1] # data harvesting passwd = spliter[2] # data harvesting Sqlrequests.connect(sockp, user, passwd, self.users) if '/q' == spliter[0]: # exit code -> logged out of the server user = spliter[1] # data harvesting print(RED + 'user[' + user + '] is off-line\n') self.broadcast_data(sockp, RED + 'user[' + user + '] is off-line\n') self.users.remove(sockp) print('\r' + str(sockp.getpeername()) + data) self.broadcast_data(sockp, '\r' + '(' + str(sockp.getpeername()) + ')' + ' ' + data) else: if sockp in self.users: self.users.remove(sockp) self.broadcast_data(sockp, 'Client({0}) is offline\r'.format(addr)) print('Client({0}) is offline\r'.format(addr)) except: self.broadcast_data(sockp, 'Client({0}) is offline\r'.format(addr)) print('Client({0}) is offline\r'.format(addr)) continue self.sock.close() if __name__ == '__main__': server = Server() server.main() |
j'ai fait une classe à part pour les options sql de connexion et d'inscription…
voici le client qui sert à se connecter grace a sys.argv:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 | import sys import socket import select import hashlib # colors for different kinds of data BLUE = '\033[94m' GREEN = '\033[92m' RED = '\033[1;31m' PURPLE = '\033[1;34m' if len(sys.argv) < 3: print(RED + '[usage] python client.py <hostname> <port> <username> <password>') sys.exit() HOST = str(sys.argv[1]) PORT = int(sys.argv[2]) USERNAME = str(sys.argv[3]) PASSWORD = hashlib.md5(str(sys.argv[4]).encode()).hexdigest() print(PURPLE + " █████╗ ██████╗ ██████╗ ███████╗███╗ ██╗ █████╗ ██╗ ██╗███╗ ██╗███████╗ \n" " ██╔══██╗██╔══██╗██╔══██╗██╔════╝████╗ ██║██╔══██╗██║ ██║████╗ ██║╚══███╔╝ \n" " ███████║██║ ██║██████╔╝█████╗ ██╔██╗ ██║███████║██║ ██║██╔██╗ ██║ ███╔╝ \n" " ██╔══██║██║ ██║██╔══██╗██╔══╝ ██║╚██╗██║██╔══██║██║ ██║██║╚██╗██║ ███╔╝ \n" " ██║ ██║██████╔╝██║ ██║███████╗██║ ╚████║██║ ██║███████╗██║██║ ╚████║███████╗ \n" " ╚═╝ ╚═╝╚═════╝ ╚═╝ ╚═╝╚══════╝╚═╝ ╚═══╝╚═╝ ╚═╝╚══════╝╚═╝╚═╝ ╚═══╝╚══════╝ \n" " hammer05 - backtrack05 / v1.0 beta / contact me hammer1.adrenalinz@yahoo.com \n") class Client: def __init__(self): self.host = HOST self.port = PORT self.run = True self.buff = 1024 self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.settimeout(2) def prompt(self): sys.stdout.write(RED + '<you> ') sys.stdout.flush() def connect(self): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) conn = (self.host, self.port) try: sock.connect(conn) while self.run: response = sock.recv(1024) sock.send(('/a' + USERNAME + ' ' + PASSWORD).encode()) if response: code = response.decode().split() if code[0] == '/at': sock.close() print('[client commands]\n' '/li: show all connected users\n' '/q: to leave the chat-room\n') self.main() except socket.error: print(RED + 'An error occurred... EXIT[1]\n') sys.exit() def main(self): try: self.sock.connect((self.host, self.port)) except socket.error: print('Unable to connect to the remote host: {0}'.format(self.host)) sys.exit() print('connected to the remote host. Start sending messages') self.prompt() while 1: rlist = [sys.stdin, self.sock] read_list, write_list, error_list = select.select(rlist, [], []) for sock in read_list: if sock == self.sock: data = self.sock.recv(self.buff).decode() if not data: print('\nDisconnected from chat server') sys.exit() if data: print('\r' + data) self.prompt() else: data = sys.stdin.readline() if data == '/q': data = data + ' ' + USERNAME self.sock.send(data.encode()) self.prompt() if __name__ == '__main__': C = Client() C.connect() |
et voici un fichier fait exprès pour s'inscrire dans la base du serveur:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 | import sqlite3 import sys import socket import hashlib # colors for different kinds of data BLUE = '\033[94m' GREEN = '\033[92m' RED = '\033[1;31m' PURPLE = '\033[1;34m' if len(sys.argv) < 3: print(RED + '[Usage] python inscriptor.py <username> <password>') sys.exit() USERNAME = sys.argv[1] PASSWORD = hashlib.md5(sys.argv[2].encode()).hexdigest() print(PURPLE + " █████╗ ██████╗ ██████╗ ███████╗███╗ ██╗ █████╗ ██╗ ██╗███╗ ██╗███████╗ \n" " ██╔══██╗██╔══██╗██╔══██╗██╔════╝████╗ ██║██╔══██╗██║ ██║████╗ ██║╚══███╔╝ \n" " ███████║██║ ██║██████╔╝█████╗ ██╔██╗ ██║███████║██║ ██║██╔██╗ ██║ ███╔╝ \n" " ██╔══██║██║ ██║██╔══██╗██╔══╝ ██║╚██╗██║██╔══██║██║ ██║██║╚██╗██║ ███╔╝ \n" " ██║ ██║██████╔╝██║ ██║███████╗██║ ╚████║██║ ██║███████╗██║██║ ╚████║███████╗ \n" " ╚═╝ ╚═╝╚═════╝ ╚═╝ ╚═╝╚══════╝╚═╝ ╚═══╝╚═╝ ╚═╝╚══════╝╚═╝╚═╝ ╚═══╝╚══════╝ \n" " hammer05 - backtrack05 / v1.0 beta / contact me hammer1.adrenalinz@yahoo.com \n") class Temporally: def __init__(self): self.host = '192.168.1.22' self.port = 4567 self.user = USERNAME self.password = PASSWORD self.run = True self.buffer = 1024 self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) def main(self): try: self.sock.connect((self.host, self.port)) except socket.error: print(RED + 'An error occurred... EXIT[1]') sys.exit() print(GREEN + 'creation of your account...\n') while self.run: response = self.sock.recv(self.buffer) self.sock.send(('/i ' + USERNAME + ' ' + PASSWORD).encode()) if response: code = response.decode().split() if code[0] == '/op': print(GREEN + 'Account created! connect to it using client.py') self.sock.close() sys.exit() elif code[0] == '/er': print(RED + 'Username already exists... use another one') sys.exit() if __name__ == '__main__': T = Temporally() T.main() |
petit problème quand je run le serveur puis le fichier d'inscription rien ne s'affiche (pas d'erreur, pas de message de succès d'inscription comme dû…) cela est-il dû au manque de thread ??? Merci et bonne soirée
+0
-0