How to call and iterate through specific indexes of a dictionary? - python

I currently have code that prints out a username and their password by means of dictionary. The output is username:abc password:12345. Right now I have them all just printing out at the same time. My main goal is to be able to email these users based on their usernames, but of course I only want to include their username and password information. Not the whole list of information. So basically I want to be able to tell the specific user only their password. For example, I would want to send an email to user abc and that email should only contain their username and password. Then I would like to send an email to user xyz but that should only contain the password of user xyz. Is there a way I can make this happen?
I currently have everything from the dictionary printing. So all the usernames and passwords are being printed out. How can I iterate through these and send an email to each user with their password?
lines = []
User_Pass = {}
#Open output file and show only lines that contain 'Success'
with open("output.txt", "r") as f:
for line in f.readlines():
#Get rid of everything in line after 'Success'
if 'Success' in line:
lines.append(line[:line.find("Success")-1])
for element in lines:
parts = element.strip().split(":")
User_Pass.update({parts[0] : parts[1]})
for key, value in User_pass.items():
print('Username: ' + key + ' Password: ' + value)
I want to be able to email each username and tell them their password. I am really not sure how to go about this. Any help would be appreciated!

Assuming you have the dictionary constructed, you just ask it for the value associated with the key, which is the username:
user_pw = User_Pass.get(username)
this will return None if the username is not in the dictionary.
Suggest you research Python dictionaries for some examples. In your loop code, you have it a little backwards as well. Anytime you want to iterate through a dictionary (the right way) you want to do it with the keys, not the items, so to loop through all in your example:
for key in User_Pass.keys():
print (key, User_Pass.get(key) )

Only fill your User_Pass dictionary when you meet "username" or "password":
for element in lines:
key, value = element.strip().split(":")
if key in {"username", "password"}:
User_Pass.update({key: value})
A simple demonstration:
lines = [
"fullname:John Doe",
"username:jdoe",
"password:S3cRet",
"age:45",
]
User_Pass = {}
for element in lines:
key, value = element.strip().split(":")
if key in {"username", "password"}:
User_Pass.update({key: value})
print(User_Pass)
You get:
{'username': 'jdoe', 'password': 'S3cRet'}
Please, you should follow the naming conventions of the PEP8: "User_Pass" => "user_pass".

Related

Dictionaries, call value from key

I am trying to grab input and if the dictionary logins has a key that matches my input, I want to return the value of that key.
logins = {
'admin':'admin',
'turtle':'password123'
}
logging = input('username: ')
for logging in logins:
print(logins.values())
Try this.
logins = {
'admin':'admin',
'turtle':'password123'
}
logging = input('username: ')
value = logins.get(logging, "Not found")
print(value)
Thanks to #deceze for kind suggestion
If you need an iteration with for, try
for login in logins:
#do something with login
# e.g. if login == input
No looping necessary, just lookup by key.
logging = input('username: ')
value = logins.get(logging)
if value is not None:
print(value)
else:
print(f"username {logging!r} was not found")
Alternatively:
print(logins[logging])
however this will raise a KeyError exception if the key logging is not in the dictionary
You're on the right path. All you need to do is make use of the native property of dictionary to find if the element is in dictionary:
logins = {
'admin':'admin',
'turtle':'password123'
}
logging = input('username: ')
if logging in logins:
print(logins[logging])

How to make a Python program automatically prints what matched after iterating through lists

I have this Python code:
with open('save.data') as fp:
save_data = dict([line.split(' = ') for line in fp.read().splitlines()])
with open('brute.txt') as fp:
brute = fp.read().splitlines()
for username, password in save_data.items():
if username in brute:
break
else:
print("didn't find the username")
Here is a quick explanation; the save.data is a file that contains variables of Batch-file game (such as username, hp etc...) and brute.txt is a file that contains "random" strings (like what seen in wordlists used for brute-force).
save.data:
username1 = PlayerName
password1 = PlayerPass
hp = 100
As i said before, it's a Batch-file game so, no need to quote strings
brute.txt:
username
usrnm
username1
password
password1
health
hp
So, let's assume that the Python file is a "game hacker" that "brute" a Batch-file's game save file in hope of finding matches and when it does find, it retrieves them and display them to the user.
## We did all the previous code
...
>>> print(save_data["username1"])
PlayerName
Success! we retrieved the variables! But I want to make the program capable of displaying the variables it self (because I knew that "username1" was the match, that's why I chose to print it). What I mean is, I want to make the program print the variables that matched. E.g: If instead of "username1" in save.data there was "usrnm", it will surely get recognized after the "bruting" process because it's already in brute.txt. So, how to make the program print what matched? because I don't know if it's "username" or "username1" etc... The program does :p (of course without opening save.data) And of course that doesn't mean the program will search only for the username, it's a game and there should be other variables like gold/coins, hp etc... If you didn't understand something, kindly comment it and I will clear it up, and thanks for your time!
Use a dict such as this:
with open('brute.txt', 'r') as f:
# First get all the brute file stuff
lookup_dic = {word.strip(): None for word in f.readlines()}
with open('save.data', 'r') as f:
# Update that dict with the stuff from the save.data
lines = (line.strip().split(' = ') for line in f.readlines())
for lookup, val in lines:
if lookup in lookup_dic:
print(f"{lookup} matched and its value is {val}")
lookup_dic[lookup] = val
# Now you have a complete lookup table.
print(lookup_dic)
print(lookup_dic['hp'])
Output:
username1 matched and its value is PlayerName
password1 matched and its value is PlayerPass
hp matched and its value is 100
{'username': None, 'usrnm': None, 'username1': 'PlayerName', 'password': None, 'password1': 'PlayerPass','health': None, 'hp': '100'}
100

Searching and sorting in text files

I am fairly new to code and i have a problem in reading a text file.
For my code i need to ask the user to type in a specific name code in order to proceed to the code. However, there are various name codes the user could use and i don't know how to make it so if you type either code in, you can proceed.
For example the text file looks like this
john123,x,x,x
susan233,x,x,x
conor,x,x,x
What i need to do is accept the name tag despite what one it is and be able to print it after. All the name tags are in one column.
file = open("paintingjobs.txt","r")
details = file.readlines()
for line in details:
estimatenum = input ("Please enter the estimate number.")
if estimatenum = line.split
This is my code so far, but i do not know what to do in terms of seeing if the name tag is valid to let the user proceed.
Here is another solution, without pickle. I'm assuming that your credentials are stored one per line. If not, you need to tell me how they are separated.
name = 'John'
code = '1234'
with open('file.txt', 'r') as file:
possible_match = [line.replace(name, '') for line in file if name in line]
authenticated = False
for item in possible_match:
if code in tmp: # Or, e.g. int(code) == int(tmp)
authenticated = True
break
You can use a module called pickle. This is a Python 3.0 internal library. In Python 2.0, it is called: cPickle; everything else is the same in both.
Be warned that the way you're doing this is not a secure approach!
from pickle import dump
credentials = {
'John': 1234,
'James': 4321,
'Julie': 6789
}
dump(credentials, open("credentials.p", "wb"))
This saves a file entitled credentials.p. You can the load this as follows:
from pickle import load
credentials = load(open("credentials.p", "rb"))
print(credentials)
Here are a couple of tests:
test_name = 'John'
test_code = 1234
This will amount to:
print('Test: ', credentials[test_name] == test_code)
which displays: {'John': 1234, 'James': 4321, 'Julie': 6789}
Displays: Test: True
test_code = 2343
print('Test:', credentials[test_name] == test_code)
Displays: Test: False

python: dictionary and if statements

I have a file to read and a dictionary.
If the file says:
sort-by username
I want the dictionary to be
d = {'sort-by': 'username'}
if the file says :
sort-by name
then I want the dictionary to be
d = {'sort-by': 'name'}
right now, I have:
if 'user' in line:
d['sort-by'] = 'username'
else:
d['sort-by'] = 'name'
however, even though the file says sort-by username, I keep getting
d = {'sort-by': 'name'}
why is this?
print dict(map(str.split,open("some_file.txt")))
assuming your file actually looks like your example
if you have any control it may be more appropriate to store your data as json

Python33 - SQLite3 accounts with authentication

I am making a webserver+website with python and I am currently figuring out how to check if your login values are correct. Previously for testing I used the following code:
def checkUser(username, password): #<-- input values go in here
site_usernames = ["admin", "username1", "username2"]
site_passwords = ["admin", "password1", "password2"]
site_couples = {"admin":"admin", "username1":"password1", "username2":"password2"}
not_counter = 0
while True:
if username in site_usernames:
if password in site_passwords:
for key in site_couples:
if (username == key) and (password == site_couples[key]):
print("User %s logged in!" % username)
return True
else:
not_counter = not_counter + 1
if not_counter > 10:
print("User failed login with accountname: %s" % username)
return False
break
else:
continue
else:
pass_exists = False
break
else:
user_exists = False
break
As far as I have seen, You can not return two columns from a database as a dictionary. I have managed to get one column as a list, and I am planning to use that.
So in my new code, I have the following:
A list of usernames that are in the database
A list of encoded passwords in the database
I would like to make an authentication function that checks if:
If the username exists in the database:
If the password exists in the database:
If the input username:password couple exists in all existing username:password values in the database:
return True if all checks succeed
The problem is that I find it very difficult to manage such a thing. As you can see in my example code, I had two lists and a dict, all pre-defined. I would like to create those things on the fly, and the only one I actually need help with is how to create the username:password dictionary couples. How would I do such a thing? zip() makes tuples and not dictionaries.
In [1]: users = ["user1", "user2"]
In [2]: pws = ["password", "12354"]
In [3]: dict(zip(users, pws))
Out[3]: {'user1': 'password', 'user2': '12354'}

Categories