Why doesn't my code read this line? - python

so I made a program that reads usernames with passwords (which are salted and hashed) from an SFTP server, and the user can log in securely. Users can also make their own accounts, but I am having a problem with the checking if the username already exists. I have managed to write the code correctly, but for some strange reason I can't find out why my code won't read one for loop, at least it doesn't print the "debug" string, example below. Any help would be appreciated!
def createUser():
f = ftp.open("paroolid.txt", "a+")
passListDecode = f.read().decode("UTF-8")
passList = passListDecode.splitlines()
newName = input("Uus kasutajanimi: ")
if len(newName) <= 0:
print("Nimi peab olema vähemalt 1 täht!")
createUser()
#This is the loop that won't be read
for line in passList:
print("debug")
pp = ""
pp += line.split(",")[1].strip().split("-")[0].strip()
pp += newName
userInFile = hashlib.md5(pp.strip().encode()).hexdigest()
if userInFile == line.split(":")[0].strip():
print("Nimi juba olemas!")
createUser()
#But this line is read successfully, like the above for loop is just being skipped.
newPass = getpass.getpass("Uus parool: ")

Everyone, I got it fixed.
I learned that you cannot use the read() function when you're using the "a+" mode while opening a file, you'll need to use seek(0).
With that the problem is answered, thanks to Mike Scotty for suggesting that the list might be empty, I didn't think of that before.

Related

How do I add user input to a list and able to see it?

I am trying to make a sign up system in python 3.7 but I don't know how to permanently add a users login to a list and not having to sign up for the same account every time you open the program.
I was not able to make up a solution to this problem.
Usernames = ['User1', 'User2']
Passwords = ['password123', 'password123']
print('Type SU to Sign Up or type LI to Log In!')
UOption = input('Option>> ')
if UOption == 'SU':
SI = True
LI = False
if SI == True:
print('Signing Up!')
SUUsername = input('Username>> ')
SUEmail = input('Email>> ')
SUPassword = input('Password>> ')
Usernames.append(SUUsername)
Emails.append(SUEmail)
Passwords.append(SUPassword)
LI = True
SI = False
I am expecting when I get this working that the user will be able to sign up once then be able to log in if they reopen the program without having to sign up again.
You could use the pickle module:
Firstly, to create the necessary files, run the following code in the folder that your program is saved in:
import pickle
pickle.dump([],open("usernames.dat","wb"))
pickle.dump([],open("emails.dat","wb"))
pickle.dump([],open("passwords.dat","wb"))
In your program, add:
import pickle
at the start of the program
Replace the lines:
Usernames = ['User1', 'User2']
Emails = ['Email1', 'Email2'] # I'm assuming this line has just been missed off your question
Passwords = ['password123', 'password123']
With:
Usernames = pickle.load(open("usernames.dat","rb"))
Emails = pickle.load(open("emails.dat","rb"))
Passwords = pickle.load(open("passwords.dat","rb"))
To read from the files
And finally add these lines at the end of your program to update the files with the new user's details
pickle.dump(Usernames,open("usernames.dat","wb"))
pickle.dump(Emails,open("emails.dat","wb"))
pickle.dump(Passwords,open("passwords.dat","wb"))
This is a link to more details on how to use pickles, if your interested
https://www.tutorialspoint.com/python-pickling
For source code including these edits see here:
https://pastebin.com/H4ryP6cT

Python Function Works just fine but doesnt work when for looped

So I Created this function that changes a UNIX users password, and it works just fine but I want to for loop a list of users to change every users password. But the for loop doesn't work in the function, When i assign a variable for the same user in the list it works just not in the loop
User.txt
FakeAccount
FakeUser
Python Function
def change_password(username, new_password):
process = pexpect.spawn("sudo passwd " + username)
process.expect("Enter new UNIX password: ")
process.sendline(new_password)
process.expect("Retype new UNIX password: ")
process.sendline(new_password)
process.close()
For Loop
np = "test"
f = open('User.txt', 'r')
for line in f:
change_password(line.strip("\n\r"), np)
print('done')
f.close()
What i'm trying to do is loop through the file and put that in place for the the username variable, when i run the code there are no errors however when i try and to login into these accounts their passwords stay the same, When i run the python script i am root so that there are not sudo password prompts.
What i think is the problem, from what I've tried
I think the problem if somwhere in the process of for-looping the file because if i run this code it works perfectly
import pexpect
def change_password(username, new_password):
process = pexpect.spawn("sudo passwd " + username)
process.expect("Enter new UNIX password: ")
process.sendline(new_password)
process.expect("Retype new UNIX password: ")
process.sendline(new_password)
process.close()
np = "test"
U = "FakeUser"
change_password(U, np)
It's only when i introduce that for loop when i get an issue, and to my knowledge its grabbing the same username as i typed in my test Example because to test that i tried
f = open('User.txt', 'r')
for line in f:
print("'" + line.strip("\n\r") + "'")
and got the results 'FakeAccount' and 'FakeUser' which means the usernames are right, is it possible that the for loop is going to fast and not sending then through the terminal? or am i missing somthing?
On first sight, it seems to me that the problem is the file opening. Try with this:
np = "test"
with open('User.txt', 'r', encoding='UTF-8') as f:
lines = [l for l in f.read().split("\n") if l]
for l in lines:
change_password(l, np)
print('done')
So after many differnt tests and changing of things it works perfect now, the issue was i was needing to run it in python3 as well as giving it some time to process the commands, when i put a time.sleep(5) in the function is ran smoothly after that.

Check variable against specific line in a text file | Python 3.6.x

Pretend I am making an email script. The user has already made a username and password, which has been stored in a text file so they can log in later at anytime.
The user needs to be able to log in. I want python to check that the users input matches the information in the text file from earlier, on their corresponding line. Capitalization doesn't matter.
The text file that was created initially reads:
johncitizen
johnspassword
My python script should read something like:
##Reads text file
guessusername = input('What is your username? ')
guesspassword = input('What is your password? ')
if guessusername.lower() = lines[0] and guesspassword = lines[1]:
##Grant access
I don't mind if capitalization is wrong, as long as the string itself matches up
Before first of all, what you are doing with plain text password storage is ill-advised. You should be using hashing+salting, or even better, pick a decent framework to work in and learn from how they do it.
First of all, your data storage format should be more record like:
user_id<tab>username<tab>password
user_id<tab>username<tab>password
user_id<tab>username<tab>password
In that case, you are able to read the file like this:
username = ... #user input
password = ... #user input
found_user_id = None
with open('pass.txt', 'rt') as f:
for line in f:
fields = line.split("\t")
if fields[1] == username and fields[2] == password:
found_user_id = fields[0]
break
#okay, here if found_user_id is not None, then you have found them
#if it is None, then you did not find them.
Truly, a database is much more useful than a text file, but this is how it works!

Python- Reading back usernames and passwords into a program to authenticate

I am currently writing a program in Python that asks if you have a log in. If no, they proceed to create a username and password. If yes, they log in and their details are checked against a text file. The text file looks like this (Username then password):
whitehallj27
EXpass%20
Username2
EXPASSWORD%%%
james_27
password1234
I am trying to figure out a way of programming this as simply as possible. It seems to work, but isn't nearly as simple and doesn't really work how I thought it would. Here is the code snippet:
logins={}
usernames_passwords=open("UsernamesAndPasswords.txt","r")
count=0
for line in usernames_passwords:
count=count+1
count=count/2
usernames_passwords.close()
usernames_passwords=open("UsernamesAndPasswords.txt","r")
try:
for x in range(count):
username=usernames_passwords.readline()
password=usernames_passwords.readline()
logins[username]=password
except TypeError:
count=int(count+0.5)
for x in range(count):
username=usernames_passwords.readline()
password=usernames_passwords.readline()
logins[username]=password
usernames_passwords.close()
print(logins)
Also, how would I go about authenticating the username and password to check it's correct.
Many thanks,
James Duxbury
Assuming that variables user and passwd have the username and password provided by the user, then just read the file in two lines:
file_contents = []
with open("UsernamesAndPasswords.txt","r") as f: #use "with", it will auotamtically close the file
file_contents = f.readlines()
usernames = file_contents[0::2] #step by 2, take all elements starting at index 0
passwords = file_contents[1::2] #step by 2, take all elements starting at index 1
found_at_index = -1
for i in range(0,len(usernames)):
if user == usernames[i] and passwd == passwrods[i]:
found_at_index = i
break
if found_at_index >= 0 :
#do whatever you want, there is match
else:
#I don't know what you wanted to do in this case
Please read this for the with keyword and this for how to read a file nicelly.
Also this about the [::] syntax.
You could create a dictionary with the user names and passwords like this:
dict = {
'user-name': 'password-hashing',
'another-user': 'another-password'
}
after you've done it you can save this dict in a json file, and load its content when the user asks for login.
the docs for handling json files with python: https://docs.python.org/3/library/json.html
obs.: it will look simpler, but its not the best way of doing this king of thing

Python Precommit hook, Looking at lines for some text

Hello, my question is regarding a Python script I am trying to get to work. The point of this is that when someone makes a SVN Commit they see a login template with four lines: Branch, Bug_Number, Feature affected and Overview. Now I am trying to write a script to make sure that they wrote something on it to make sure no one enters a empty log to commit.
Here is what I have so far in python its based on a old python script.
print "Importing the items"
import re
import sys
import os
print "Initializing the list."
argsList = []
hndFile = open(sys.argv[1],"r")
for line in hndFile:
argsList.append(line)
hndFile.close()
print "Checking what is blank"
faOK = ovOK = False
for line in argsList:
line = line.strip()
if line.startswith('FEATURE_AFFECTED:'):
faOK = line[17:] != ''
if line.startswith('OVERVIEW:'):
ovOK = line[9:] != ''
if not faOK:
print "You Must Enter the Feature Affected"
ret = -1
elif not ovOK:
print "You Must Enter an Overview of the Fix"
ret = -1
else:
ret = 0
print "Finishing the script"
sys.exit(ret)
Any advice would help. I am using Windows XP and currently nothing is happening. I am also using collabnet svn. Currently nothing is happening when I try to run this script. I know I haven't added svnlook in the script I cant really think of where to add and for the variable for it. Thank you.

Categories