Easier way to simplify? - python

Trying to write a script to simplify my cisco configs. User inputs names and passwords and the script will add them all together in a line by line document i can copy and paste from.
This is the method i've chosen (very new with python) and was wondering if there was a simpler way with functions or anything else?
hostname = input("Enter Hostname?" '\n')
en_secret = input("Enter Enable Password" '\n')
en_secret_script = "enable secret {}".format (en_secret)
hostname_script = "hostname {}".format(hostname)
script = '\n'.join([hostname_script, en_secret_script])
print(script)

You can get the same result with less line like this:
hostname = input("Enter Hostname?" '\n')
en_secret = input("Enter Enable Password" '\n')
print(f"hostname {hostname} \nenable secret {en_secret}")

Related

Trying to find out which line something is in a file and applying it to something else

I'm very new to this so sorry if I'm doing it wrong.
I'm trying to make a create account/login system and I'm using two separate .txt files to store the usernames and passwords.
When the usernames are created, the passwords are added to the corresponding lines on the other file. Once I've verified that the username is correct, I am trying to work out which line the username is on in my file so that I can find the correct password for that username.
Could someone help me find a way to find the line that the username is on and use that to check if the password is the correct password for that particular username?
username = input("Please enter your username: ")
with open("usernames.txt", "r") as loginfile:
if (username + "\n") in loginfile.readlines():
password = input("Please enter your password: ")
with open("passwords.txt", "r") as loginfile:
if (password + "\n") in loginfile.readlines():
print("Welcome!")
This works completely fine, but if I used this, then someone could type in a correct username and a correct password, but the password isn't the password that is linked to that username, even though it is a correct password.
It's hard to describe but I hope that makes sense!
Please help if you can!!!
You will need to get the line number. You could use the index method of a list to find which item matches. (This will raise ValueError if none of them match.) Then you can index the list of passwords (with newlines) on the line number of interest.
username = input("Please enter your username: ")
with open("usernames.txt", "r") as loginfile:
try:
line_number = loginfile.readlines().index(username + "\n")
except ValueError:
line_number = None
if line_number is not None:
password = input("Please enter your password: ")
with open("passwords.txt", "r") as loginfile:
if (password + "\n") == loginfile.readlines()[line_number]:
print("Welcome!")
Note that in reality you would probably still want to prompt for a password even if the username does not exist and therefore the login has no chance of succeeding, because otherwise you give away too much information to somebody who is trying a brute force attack (guessing usernames and passwords) by making it possible for them to know whether the username that they are trying is valid or not. This could easily be achieved by moving the password = input(...) line to before the if block.

How to save output in python to .txt file

So basically i bought a book that teaches the basics of python and how to create a random number generator so I decided to go one step further and make a random password generator I found a tutorial online that gave me a good example of why and what is used to make a password generator but i want the output to be saved to a .txt file I do not know what i need to implement to get the result i want this is what i have i'm using python3.
import random
chars = 'abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!, #,#$%^&*.'
number = input('Number of passwords - ')
number = int(number)
length = input('password length? - ')
length = int(length)
answer = input
for P in range(number):
password = ''
for C in range(length):
password += random.choice(chars)
print(password)
password = open("passlist.txt", "a")
password.write(password)
password.close()
file = open('passlist', 'w')
file.write(password)
file.close()
this is what i get in shell
Traceback (most recent call last):
File "C:\User\Desktop\passgen.py", line 21, in <module>
password.write(password)
TypeError: write() argument must be str, not _io.TextIOWrapper
When you open a new file and set it equal to a variable, you are actually creating an _io.TextIOWrapper object. So in this line of code, you are creating this object and storing it in password, getting rid of the password generated in the previous lines of code.
password = open("passlist.txt", "a")
You are then trying to write to the passlist.txt file with this line:
password.write(password)
You are telling password, now an _io.TextIOWrapper object, to write to the passfile.txt the _io.TextIOWrapper object, not the password generated beforehand. This function is expecting a string, and you are now passing an _io.TextIOWrapper object. Since password is no longer a string, that is why you are running into the error.
To fix this, I would suggest creating a new variable:
txtFileWriter = open("passlist.txt", "a")
txtFileWriter.write(password)
txtFileWriter.close()
You may find that after fixing this, only one value is being stored inside your text file. I would recommend properly nesting your for loops:
for P in range(number):
password = ''
for C in range(length):
password += random.choice(chars)
print(password)
The meaning of these for loops can be translated as:
For each password, set the password = ' ' and for each character, add one random character to password.
The problem with this is that you will only have one password after the for loops are complete. You are setting the password value to ' ' each time you run through the outer loop. The only password that will be saved, will be the last value. In order to fix this, I recommend using a list.
I recommend reading through this documentation
I don't want to spoon feed the answers since I realize you are learning python, so I will leave it here. You will want to create a list and then append a value to that list each time you generate a password. After some reading, hopefully this will make sense.
filename = 'passlist.txt'
with open (filename, 'a') as file_object:
file_object.write(password)
Using with will close the file once access is no longer needed.
You also need a list to append your passwords ;)
The error originates from password being re-assigned in password = open("passlist.txt", "a"). This causes and error in the next line as you are attempting to pass password as parameter to itself in password.write(password).
Some farther assistance
You have the right idea but you forgot to indent. All the lines below for P in range(number): should be indented because the program must generate and write a new password until it has satisfied the required amount of passwords.
The password = open("passlist.txt", "a")
password.write(password)
password.close() lines are unnecessary as you are overriding the generated password and assigning that password variable to something that is not a string; that is why you are getting that error.
Here is the code with the adjustments.
import random
chars = 'abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!, #,#$%^&*.'
number = input('Number of passwords - ')
number = int(number)
length = input('password length? - ')
length = int(length)
answer = input
for P in range(number):
password = ''
for C in range(length):
password += random.choice(chars)
print(password)
password += "\n" # writes the password in a new line
file = open('passlist.tx', "a")
file.write(password)
file.close()

Storing a username and password, then allowing user update. Python [duplicate]

This question already has answers here:
I need to securely store a username and password in Python, what are my options? [closed]
(8 answers)
Closed 5 years ago.
I am trying to create a program that asks the user for, in this example, lets say a username and password, then store this (I assume in a text file). The area I am struggling with is how to allow the user to update this their password stored in the text file? I am writing this in Python.
import getpass
import os
import bcrypt
new=None
def two_hash():
master_key = getpass.getpass('enter pass word ')
salt = bcrypt.gensalt()
combo = salt + master_key
hashed = bcrypt.hashpw(combo , salt)
allow = raw_input('do you want to update pass ')
if allow == 'y':
new = getpass.getpass('enter old pass word ')
combo = salt + new
bcrypt.hashpw(combo , salt)
if ( bcrypt.hashpw(combo , salt) == hashed ):
new = getpass.getpass('enter new pass ')
print new
else :
pass
if __name__ == '__main__':
two_hash()
Note 1 : i wanted to split my code to some function but i can't so help for split it to some function
Because you've asked to focus on how to handle the updates in a text file, I've focused on that part of your question. So, in effect I've focused on answering how would you go about having something that changes in a text file when those changes impact the length and structure of the text file. That question is independent of the thing in the text file being a password.
There are significant concerns related to whether you should store a password, or whether you should store some quantity that can be used to verify a password. All that depends on what you're trying to do, what your security model is, and on what else your program needs to interact with. You've ruled all that out of scope for your question by asking us to focus on the text file update part of the problem.
You might adopt the following pattern to accomplish this task:
At the beginning see if the text file is present. Read it and if so assume you are doing an update rather than a new user
Ask for the username and password. If it is an update prompt with the old values and allow them to be changed
Write out the text file.
Most strategies for updating things stored in text files involve rewriting the text file entirely on every update.
Is this a single user application that you have? If you can provide more information one where you're struggling
You can read the password file (which has usernames and passwords)
- When user authenticate, match the username and password to the combination in text file
- When user wants to change password, then user provides old and new password. The username and old password combination is compared to the one in text file and if matches, stores the new
Try using JSON.
An example of a json file would be this:
{
"Usernames": {
"Username": [
{
"Password": "Password123"
}
]
}
}
Then to edit the json:
jsonloads = json.loads(open('json.json').read()) #Load the json
username = input("Enter your username: ") #Get username as a string
for i in jsonloads["Usernames"]: #Iterate through usernames
if i == username: #If the username is what they entered
passw = input("New password: ") #Ask for new password
jsonloads["Usernames"][i][0]["Password"] = passw #Set the password
jsonFile = open("json.json", "w+") #Open the json
jsonFile.write(json.dumps(jsonloads, indent=4)) #Write
jsonFile.close() #Close it
break #Break out of the for loop
else: #If it remains unbroken
print("You aren't in the database. ")
user = input("Username: ") #Ask for username
passw = input("Password: ") #Ask for password for username
item = {"Password":pass} #Make a dict
jsonloads["Usernames"].update({user: item}) #Add that dict to "Usernames"
with open('json.json','w') as f: #Open the json
f.write(json.dumps(jsonloads, indent=4)) #Write
Something like that should work, haven't tested it though.
Also, remember to always encrypt passwords!

How can i get my code to test just one line in a text file?

Hello i am looking for some help. so for some back ground this code is going to be used as a log in system for personal use. i am trying to get it to check just one line so i can get it to validate that the username is correct and or the password. how would i do this?
user = input("please Enter your full name: ")
if os.path.isfile(user + ".txt"):
with open(user + ".txt", "r")
print("------------------------")
Username = input("|Username: ")
password = getpass.getpass("|Password: ")
print("------------------------")
Ok, if you insist on doing it in an insecure way then I guess you have just a file with a plaintext user name and password in it. I understand that perhaps you are knew to Python so an insecure method is somewhat acceptable :P. Example below,
bosh
password
(in the file there would be no gap between lines as shown above, they would be on consecutive lines)
If not then I recommend you do this as this is how the code section below will expect it to be.
submittedUsername = input("Please enter username: ")
submittedPassword = input("Please enter password: ")
credentialsFile = open("credentials.txt", "r")
credentials = credentialsFile.readlines()
username = credentials[0].rstrip("\n\r")
password = credentials[1].rstrip("\n\r")
if submittedUsername == username:
if submittedPassword == password:
print("Login verified!")
#both username and password verified here, do what you want
else:
#password incorrect
print("Login invalid")
else:
#username incorrect but whether you want to specify what is wrong is up to you
print("Login invalid")
If there are any parts you would like explaining, do ask. Hope that helps.

txt file to dictionary and login implementation Python 3

I am attempting to create a login script. I have the usernames and passwords in a text file that I want python to read and check through to find usernames and passwords.
The biggest problem I am having is "attaching" the password to a username. I can currently only scan the whole of the document for both but not necessarily attached to each other.
#-------------------------------------------------------------------------------
# Name: LogIn
# Purpose: Logging In
#
# Author: Dark Ariel7
#
# Created: 19/02/2013
# Copyright: (c) Dark Ariel7 2013
# Licence: I take no responsability for anything.
#-------------------------------------------------------------------------------
from getpass import getpass
from time import sleep
Database = open("C:\\Users\Dark Ariel7\\Desktop\\USB BAckup\\Scripts\\Database.txt", encoding='utf-8')
Username = ("")
Password = ()
def LogIn():
Database = open("C:\\Users\Dark Ariel7\\Desktop\\USB BAckup\\Scripts\\Database.txt", encoding='utf-8')
Data = (Database.read())
Username = ("")
Password = ()
Username = input("Username: ")
Password = getpass(str("Password: "))
LogIn= ",".join((Username,Password))
if LogIn in Data:
print("Welcome, " + Username)
sleep(3)
pass
else:
print("Failed, Sucker!")
sleep(5)
exit()
LogIn()
If you guys could help me figure out what exactly .join part is for that would be great. Should i make a dictionary and use the index for a login sheet? I also want some general feedback on how to make the code better.
This is the txt file that it will be reading:
[Dark Ariel7,123456]
[Poop,Anko]
*Edit Sorry guys I forgot to mention that I am using python 3 not 2. Thanks so far. Very quick replies. Also after the last else instead of exit what do I put so that the function loops until I get the right username password combo?
The ".join" part joins the username and password that the user types in with a comma between them (i.e. Poop,Anko) because that's the format in which it's stored in the database, so you can search for it that way.
Here's your code, edited up a bit, with some comments about functionality and style.
from getpass import getpass
from time import sleep
Database = open("C:\\Users\Dark Ariel7\\Desktop\\USB BAckup\\Scripts\\Database.txt", encoding='utf-8')
# These next two lines aren't necessary - these variables are never used; you may want to read up about namespaces: http://bytebaker.com/2008/07/30/python-namespaces/
#Username = ("")
#Password = ()
def LogIn():
Database = open("C:\\Users\Dark Ariel7\\Desktop\\USB BAckup\\Scripts\\Database.txt", encoding='utf-8')
# Removed the parentheses; they have no effect here. Putting parens around lone statements doesn't have any effect in python.
Data = Database.read()
# These next two lines are pointless, because you subsequently overwrite the values you give these variables. It looks like you're trying to "declare" variables, as you would in Java, but this isn't necessary in python.
# Username = ("")
# Password = ()
# Changed this from "input" to "raw_input" because input does something else that you don't want.
Username = raw_input("Username: ")
Password = getpass(str("Password: "))
LogIn= ",".join((Username,Password))
if LogIn in Data:
print("Welcome, " + Username)
# Not sure why you want the script to sleep, but I assume you have your reasons?
sleep(3)
# no need to pass
# pass
else:
print("Failed, Sucker!")
sleep(5)
# exit() isn't necessary - the function will end by itself.
# exit()
LogIn()
The basic problem you have is that your file has [ ] surrounding the username and password combination, but you fail to account for this.
There are some other stylistic issues with your code, here is an edited version:
import getpass
from time import sleep
password_file = r'C:\....\Database.txt'
def login(user,passwd):
''' Checks the credentials of a user '''
with open(password_file) as f:
for line in f:
if line.strip(): # skips blank lines
username,password = line.split(',') # this gets the individual parts
username = username[1:] # gets rid of the [
password = password[:-1] # the same for the password
if user == username and password == passwd:
return True
return False
if __name__ == '__main__':
username = input('Please enter the username: ')
passwd = getpass('Please enter the password: ')
if login(user,passwd):
print('Welcome {1}'.format(user))
sleep(3)
else:
print('Failed! Mwahahaha!!')
sleep(5)
To start off with, you don't need () to "initialize" variables; more to the point in Python you don't need to initialize variables at all. This is because Python doesn't have variables; but rather names that point to things.
Next, the python style guide says that variable names should be lowercase, along with method names.
Now - the main part of the code:
>>> username, password = '[username,sekret]'.split(',')
>>> username
'[username'
>>> password
'sekret]'
I used split() to break up the line into the username and password parts; but as you see there is still the [ messing things up. Next I did this:
>>> username[1:]
'username'
>>> password[:-1]
'sekret'
This uses the slice notation to strip of the leading and ending characters, getting rid of the [ ].
These lines:
with open(password_file) as f: # 1
for line in f: # 2
if line.strip(): # skips blank lines
Do the following:
Opens the file and assigns it to the variable f (see more on the with statement)
This for loop steps through each line in f and assigns the name line to each line from the file.
The third part makes sure we skip blank lines. strip() will remove all non-printable characters; so if there are no characters left, the line is blank and will have a 0 length. Since if loops only work when the condition is true, and 0 is a false value - in effect what happens is we only operate on non-blank lines.
The final part of the code is another if statement. This is a check to make sure that the file will run when you execute it from the command prompt.

Categories

Resources