Python socket programming - Counting attempts does not work - python

I am trying to program a login system using the library 'socket'. With six failed attempts the server side should do some stuff, but the failed attempts are not counted. Thanks if you can help me.
Client side:
# login logic
while True:
# Generate hashed password
password = input("Password: ")
hashed_password = hashlib.sha512(password.encode()).hexdigest()
s.sendall(hashed_password.encode())
is_password_correct = s.recv(1024)
if is_password_correct.decode() == "correct_password":
print(f"{green_sign} You have successfully authorized!")
break
elif is_password_correct.decode() == "wrong_password":
password_trials = s.recv(1024)
print(f"{yellow_sign} Wrong password! Try again... ({int(password_trials.decode())} / 6)")
Server side:
# login logic
password_trials = 0
while True:
# check hashed password
recv_password = conn.recv(1024)
if recv_password.decode() == stored_hashed_password:
password_trials = 0
print(f"{gray_sign} User has authorized successfully!")
conn.sendall(b"correct_password")
break
elif recv_password.decode() != stored_hashed_password:
password_trials += 1
conn.sendall(b"wrong_password")
conn.sendall(str(password_tries).encode())
if password_trials == 6:
""" Do some stuff """

Related

Python program to register accounts an log in

So I'm making a program where I need a user to log in or register. The registered account goes to a .txt file from which I'm supposed to read the data to log in again.
I managed to get the basics working. I can register a new account to the file and I can log in with every account I've created, but I can't seem to get 2 important elements working. The first one is for when the user inserts an inexistent username/ password (in this case the program just does nothing as I can't figure out a condition to make it go back to asking the username and password), and the second one is for when I insert a username and password that don't match. Here the program goes back and asks for them again but then keeps asking, even if I put them correctly.
Here's my function if anyone's interested in having a look at it:
def ent():
util = False
ppass = False
login = False
while not login:
n_util = input("Introduce your username: ")
password = input("Introduce your password: ")
with open("dadoscontas.txt", "r") as f:
while not util:
vski = 0
for line in f:
vski += 1
if vski == 1:
if line.strip() == n_util:
util = True
else:
break
if vski == 2:
if line.strip() == password and user:
ppass = True
if user and ppass:
login = True
print("Logged in")
I've spent my whole afternoon trying different things to see if I can get these 2 things to work, but I can't. As I said, the function above is the part that kinda works, and if anyone could give any suggestions / point me in the right direction it would be really helpful. Thank you in advance.
Does this code cover your needs?
def ent():
util = False
login = False
while not login:
n_util = input("Introduce your username: ")
password = input("Introduce your password: ")
with open("some_test.txt", "r") as f:
vski = 0
for line in f:
vski += 1
if vski%2:
if line.strip() == n_util:
util = True
elif util:
if line.strip() == password:
login = True
else:
util = False
print("Logged in")
Or you even could exit the function with return in if line.strip() == password: block.
But i would recommend you to store the file content to dictionaries (user_name:passwor),
because you are parsing the whole file again and again while login=False:
def ent():
login = False
name=""
my_data = {}
with open("some_test.txt", "r") as f:
index = 0
for line in f:
index += 1
if index%2:
name = line.strip()
else:
my_data[name] = line.strip()
while not login:
n_util = input("Introduce your username: ")
password = input("Introduce your password: ")
if n_util in my_data and my_data[n_util] == password:
login = True
print("Logged in")
If you use python2 you can use .get() or try instead of n_util in my_data for better performance.

Program keeps putting out weird results

I am having a problem with my program where my server receives data that I am NOT sending from my client
Connection from: ('192.168.0.17', 58167)
data recieved : __UserLogin123__
User Login requested
James Green at recieve login
James Green in accessCodes
93
{93: ['James', 'Green']}
Found
User Found
3
data recieved : __QUIT____CHECK_SCORE__
Incorrect code received
done
Connection from: ('192.168.0.17', 58182)
data recieved : __UserLogin123__
User Login requested
James Green at recieve login
James Green in accessCodes
93
{93: ['James', 'Green']}
Found
User Found
3
data recieved : __QUIT____CHECK_SCORE__
Incorrect code received
the last "data recieved : QUIT___CHECK_SCORE" makes absolutely no sense, I use codes to access methods from classes which will send certain types of data telling the server if i want to (for example) add a user to a database, and it does this by accessing a dictionary storing methods with string keys.
Here is the "handler" and "main" from my client:
def Main():
global s
host = "192.168.0.17"
port = 5000
ID = "__UserLogin123__"
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.connect((host, port))
s.send(str.encode(ID))
setupCheck = s.recv(2048).decode()
time.sleep(1)
if setupCheck == "__dataReceived__":
username = input("Enter username : ")
password = input("Enter password : ")
userDetails = (username, password)
dataString = pickle.dumps(userDetails)
s.send(dataString)
access = s.recv(2048).decode()
print(access)
if access == "__ACCESS_GRANTED__":
permissionLvl = s.recv(2048).decode()
print(permissionLvl)
if permissionLvl == "1":
ClientUser = User(username,password)
elif permissionLvl == "2":
ClientUser = Admin(username,password)
elif permissionLvl == "3":
ClientUser = HeadAdmin(username,password)
else:
print("SOMETHING WRONG SOMETHING WROGN")
time.sleep(3)
handler(ClientUser)
else:
print("Incorrect details provided")
def handler(ClientUser):
function_dict = {"__QUIT__": ClientUser.quit(), "__PLAY_GAME__": ClientUser.playGame(),
"__CHECK_SCORE__": ClientUser.checkScore(),"__CHECK_USERS__": ClientUser.checkUsers(),
"__ADD_ASSIGNMENT__": ClientUser.addAssignment(),"__REMOVE_ASSIGNMENT__": ClientUser.removeAssignment(),
"__EDIT_ASSIGNMENT__": ClientUser.editAssignment(), "__ADD_USER__": ClientUser.addUser(),
"__EDIT_USER__": ClientUser.editUser(), "__REMOVE_USER__": ClientUser.removeUser(),
"__CREATE_GROUP__": ClientUser.createGroup()}
while True:
checkDataReady = s.recv(2048).decode()
print(checkDataReady)
if checkDataReady == "__dataExchangeReady__":
print("Available Commands:")
ClientUser.availableCommands()
commandChoice = ""
while commandChoice not in choices:
while True:
try:
commandChoice = int(input("Please enter your choice (number) \n-> "))
except ValueError:
print("Please only enter integers")
finally:
if commandChoice > 14 or commandChoice < 0:
print("Please only enter one of the numbers listed")
else:
break
commandChoice = choices[commandChoice]
print(commandChoice)
checkString = "Are you sure you want to : " + commandChoice + "? (Y/N) -> "
check = input(checkString)
if check.upper() == "N":
commandChoice = ""
print("executing function")
function_dict[commandChoice]
and here is some server side code that I think is affiliated with the problem:
def handler(conn, addr):
print("done")
print("Connection from: " + str(addr))
dbSetup()
while True:
time.sleep(1)
data = conn.recv(2048).decode()
print("data recieved : " + data)
if data == "__QUIT__" or not data:
print("Connection closed")
print("Connection Closed by", addr[0], ":", addr[1])
break
elif data in accessCodes:
accessCodesHandler(data)
elif data in commandCodes:
commandCodesHandler(data)
else:
print("Incorrect code received")
break
conn.send(str.encode("__dataExchangeReady__"))
conn.close()
def accessCodesHandler(accessCode):
if accessCode == accessCodes[0]:
print("User Login requested")
username, password = receiveLoginDetails()
print(username,password, "in accessCodes")
userCheck = getUser_InHash(username, password)
if userCheck == True:
userPermissionLvl = str(getUser_InUserDb(username,"")[2])
print("User Found")
conn.send(str.encode("__ACCESS_GRANTED__"))
time.sleep(1)
print(userPermissionLvl)
conn.send(str.encode(userPermissionLvl))
else:
print("User not found")
conn.send(str.encode("__AccessDenied__"))
else:
print("Head admin setup protocol executed")
username, password = receiveLoginDetails()
addUser_InHash(username, password, 3)
I can see no reason why my server would ouput "QUIT__CHECK_SCORE" as i dont send any data that says that explicitly, my error code for client side is:
Enter username : James
Enter password : Green
__ACCESS_GRANTED__
3
James
Green
Traceback (most recent call last):
File "C:/Users/Green/Desktop/Py Proj/Project_Client.py", line 197, in <module>
Main()
File "C:/Users/Green/Desktop/Py Proj/Project_Client.py", line 153, in Main
handler(ClientUser)
File "C:/Users/Green/Desktop/Py Proj/Project_Client.py", line 161, in handler
"__ADD_ASSIGNMENT__": ClientUser.addAssignment(),"__REMOVE_ASSIGNMENT__": ClientUser.removeAssignment(),
File "C:/Users/Green/Desktop/Py Proj/Project_Client.py", line 37, in removeAssignment
s.send(str.encode("__REMOVE_ASSIGNMENT__"))
ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host
Process finished with exit code 1
Sorry if this isnt enough information, I really dont know what is wrong with the program. Thanks in advance for any help
Your dictionary initialization code is suspect.
The following actually invokes funca() and stores its return value as the value associated with the key 'a':
d = { 'a': funca() }
If you want to store the funca function itself, for later lookup and invocation, then use:
d = { 'a': funca }

csv - Creating a login system, python not properly reading from .csv file?

I am trying to make a login system that is looped basically and whenever I try to enter the correct details that are even stored in the .csv file, it outputs as incorrect username/password no matter what I put. This code works for python 3.6 but I need it to work for python 3.2.3.
loop1 = False #for this bit of code (logging in)
loop2 = False #for next bit of code
while loop1 == False:
choice = input("Login/SignUp [TYPE 'L' OR 'S']: ").lower()
if choice == "l":
username = input("Username: ")
password = input("Password: ")
f = open("usernamepassword.csv","r")
for line in f:
details = line.split(",")
if username == details[0] and password == details[1]:
print("Welcome")
break
#this whole bit of code is meant to read from the csv and check if the login details are correct
else:
print("Username/Password [INCORRECT]")
Allow me to refactor your code:
def login(username, password):
with open("usernamepassword.csv", "r") as csv:
all_details =
[[attr.strip() for attr in line.split(",")]
for line in csv]
return any(
username == details[0]
and password == details[1]
for details in all_details)
def login_action():
username = input("Username: ")
password = input("Password: ")
if not login(username, password):
raise ValueError("Username/Password [INCORRECT]")
return True
_USER_ACTIONS = {
'l': login_action
}
def main():
while True:
choice = input("Login/SignUp [TYPE 'L' or 'S']: ").lower()
action = _USER_ACTIONS[choice]
try:
if action():
break
except Exception as err:
print(err.message)
I think your unexpected behavior comes from not stripping the values you get after splitting by ,
Solved by replacing:
if username == details[0] and password == details[1]:
With:
if username == details[0] and (password+"\n") == details[1]:
You may have a bug in line.split(','), try line.strip().split(',')
TL; DR: posted a proper solution there : https://github.com/cgte/stackoverflow-issues/tree/master/47207293-csv-dict
I'll stuff up my answer later if needed.
Furthermore you have a poor code design here, and find yourself debugging in the middle of a loop.
So first of all : load the data file, store content to a dict.
f = open("usernamepassword.csv","r")
for line in f:
details = line.split(",")
if username == details[0] and password == details[1]:
print("Welcome")
break
Should become
user_pass = {}
f = open("usernamepassword.csv","r")
for line in f:
user, password = line.strip().split(",")
user_pass[user] = password
f.close()
or better
with open("usernamepassword.csv","r") as f:
for line in f.readlines():
user, password = line.split().split(",")
user_pass[user] = password
eventually run python -i yourfile.py and type "user_pass" to see what is actually stored when correct go on further code.
Think of using the csv module : https://docs.python.org/3/library/csv.html
Then get username and password from input and check:
if login in user_pass and user_pass[login] = password:
# or better `if user_pass.get(login, None) == password:`
do_stuff()

Can't verify password using passlib

So I'm back working on old project and I cant find whats wrong.
This is the part where the password is first time created, this is from the main script:
def first():
if os.path.isfile("secret.txt"):
folder()
else:
os.system("echo > secret.txt")
password = getpass.getpass("Set your password please --> ")
while len(password) < 4:
print("Password must have more then 4 characters!")
else:
password1 = getpass.getpass("repeat your password please --> ")
while password1 != password:
print("Password don't match")
password1 = getpass.getpass("repeat your password please --> ")
if password1 == password:
a = open('secret.txt', 'w').close()
f = open('secret.txt', 'w')
hashed_password = pbkdf2_sha256.hash(password)
f.write(hashed_password)
os.system("attrib +h secret.txt")
folder()
This is the login script and from here is password checked:
def log_in():
f = open("secret.txt", "r")
Password = f.read()
x = 0
while x < 5:
getPass = getpass.getpass("Password:")
if not pbkdf2_sha256.verify("getPass", Password):
print("Password is invalid")
x = x + 1
else:
f.close()
os.system('cls')
print("Welcome back sir\n")
x = 10
time.sleep(2)
if x == 5:
print("acces denied")
time.sleep(5)
os.system("nothing.bat")
So the problem is when I try to verify the password it says its not correct but the password is the same. In doc it says:
Note that since each call generates a new salt, the contents of the resulting hash will differ between calls (despite using the same password as input):
If this is the problem at .verify() then what should I do?
I'm not sure if this is enough info, if not I will post whole source code
I am probably missing some stupid thing but I just cant seem to find it..
I think the problem is:
if not pbkdf2_sha256.verify("getPass", Password):
Change it to:
if not pbkdf2_sha256.verify(getPass, Password):
You have called a str "getPass" not the password that user input.

Python imports module but doesn't recognize it when i initiate it?

I honestly have no idea why this is happening, I assume due to it not being on stack-exchange it's a very n00by mistake on my part. so here's the error:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
UnboundLocalError: local variable 'socket' referenced before assignment
tcpServer.py
import socket
def Main():
UID = 1001
sockets = []
users = [] ## create usernames list
sessionLimit = input("session Queue Limit: ")
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('192.168.1.74', 12127))
s.listen(sessionLimit) ## listen for 1 connection at a time
while True:
c, addr = s.accept()
sockets.append(c)
users.append(c.recv(1024).decode('utf-8'))
print("Connection from " + str(addr))
data = c.recv(1024).decode('utf-8') ## recieve 1024 bytes from client at a time, and then decode it into utf-8
if not data:
break
temp == data
temp.split(" ")
if temp[0] == "//": ## check to see if user has sent command
if temp[1] == "msg":
for i in range(len(users)):
if users[i] == temp[2]:
sockets[i].send((" ".join(temp[::2])).encode('utf-8'))
else: ## else, send data to all users. Could just use s.sendall(data.encode('utf-8'))
for socket in sockets:
socket.send(data.encode('utf-8')) ## send to sockets[socket]
##print("From connected user: " + data)
##data = data.upper()
##print("Sending: " + data)
##c.send(data.encode('utf-8'))
## command listening
commands = input("-> ")
commands.split(" ")
if commands[0] == "exit":
c.close() ## close connection
elif commands[0] == "/msg":
for i in range(len(users)):
if users[i] == commands[1]:
sockets[i].send((" ".join(commands[::1])).encode('utf-8'))
"""
elif commands[0] == "/rename": ## dont implement yet, due to users[] length changing
for i in range(len(users)):
if users[i] == commands[1]:
sockets[i].send("<server_" + UID + "> rename " + commands[2].encode('utf-8'))
"""
c.close()
if __name__ == "__main__":
Main()
Thanks for any help !
- Jacob
The issue is that you're using the variable name socket in the context of your Main() function when you do the following code block:
for socket in sockets:
socket.send(data.encode('utf-8')) ## send to sockets[socket]
That's causing an naming issue with the socket library. If you change that to:
for sock in sockets:
sock.send(data.encode('utf-8')) ## send to sockets[socket]
It will start to work. I also had to indent your code differently to ensure it was all in the Main() function you set up, and had to ensure the input() was parsed as an int. For reference, here's the full code block working for me:
import socket
def Main():
UID = 1001
sockets = []
users = [] ## create usernames list
sessionLimit = int(input("session Queue Limit: "))
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('192.168.1.74', 12127))
s.listen(sessionLimit) ## listen for 1 connection at a time
while True:
c, addr = s.accept()
sockets.append(c)
users.append(c.recv(1024).decode('utf-8'))
print("Connection from " + str(addr))
data = c.recv(1024).decode('utf-8') ## recieve 1024 bytes from client at a time, and then decode it into utf-8
if not data:
break
temp == data
temp.split(" ")
if temp[0] == "//": ## check to see if user has sent command
if temp[1] == "msg":
for i in range(len(users)):
if users[i] == temp[2]:
sockets[i].send((" ".join(temp[::2])).encode('utf-8'))
else: ## else, send data to all users. Could just use s.sendall(data.encode('utf-8'))
for sock in sockets:
sock.send(data.encode('utf-8')) ## send to sockets[socket]
##print("From connected user: " + data)
##data = data.upper()
##print("Sending: " + data)
##c.send(data.encode('utf-8'))
## command listening
commands = input("-> ")
commands.split(" ")
if commands[0] == "exit":
c.close() ## close connection
elif commands[0] == "/msg":
for i in range(len(users)):
if users[i] == commands[1]:
sockets[i].send((" ".join(commands[::1])).encode('utf-8'))
"""
elif commands[0] == "/rename": ## dont implement yet, due to users[] length changing
for i in range(len(users)):
if users[i] == commands[1]:
sockets[i].send("<server_" + UID + "> rename " + commands[2].encode('utf-8'))
"""
c.close()
if __name__ == "__main__":
Main()

Categories