This is a simple program that prompts for the length of passwords, and how many passwords are to be created. I need to print the results to a file. However, it is printing all of the results into one line. See below.
Here is the code:
import string
import random
print('''---Password Generator---''')
characters = string.punctuation + string.ascii_letters + string.digits
numofpasswd = int(input('How many passwords would you like?: '))
passwdlength = int(input('Please pick amount of characters. Pick more than 8 characters for better security: '))
if passwdlength < 8:
print("Password is less than 8 characters. Please restart program.")
else:
for password in range(numofpasswd):
passwd = ''
for char in range(passwdlength):
passwd += random.choice(characters)
print(passwd)
f = open("pass.txt", 'a')
f.write(passwd)
f = open('pass.txt', 'r')
f.close()
Here is a sample output. I requested 2 passwords with a length of 9:
~Lf>8ohcY
Q*tPR:,
Here is what is written to pass.txt:
~Lf>8ohcYQ*tPR:,
As you can see, it combines the output. Please help.
extra: is there a way to simplify this code as well? Thanks!
Write a newline after each password:
f.write(passwd + '\n')
Also, you shouldn't do
f = open('pass.txt', 'r')
before
f.close()
Related
my goal for this code is to generate a random set of passwords after answering a few command prompt question, to save those passwords to a text document to be viewed/edited later. Im running into an issue where the text document doesn't actually get edited and after reading through some similar questions; made some adjustments. I still need help though!
for password in passwords:
with open('SavedPasswords.rtf' , 'a') as f:
#the following loops create the password(s) and print them to console
if special_chars == "YES" :
for pwd in range(amount):
passwords = ''
for c in range(length):
passwords += random.choice(chars)
print(passwords)
f.write(passwords)
elif special_chars == "NO" :
for pwd in range(amount):
passwords = ''
for c in range(length):
passwords += random.choice(chars2)
print(passwords)
f.write(passwords)
This is what work for me when re-constructing your case:
import random
import string # For string module
passwords = ["", "", "", ""]
special_chars = "YES" # Just for testing
amount = 2
length = 10
# Use the string module to get all ascii char
with_punctuation = string.ascii_letters + string.punctuation
without_punctuation = string.ascii_letters
for password in passwords:
with open('SavedPasswords.rtf' , 'a') as f:
if special_chars == "YES" :
for pwd in range(amount):
passwords = ''
for c in range(length):
passwords += random.choice(with_punctuation)
print(passwords)
f.write(passwords + "\n") # Add this to separate them, I think a csv is better!
elif special_chars == "NO" :
for pwd in range(amount):
passwords = ''
for c in range(length):
passwords += random.choice(without_punctuation)
print(passwords)
f.write(passwords + "\n")
You didn't tell exactly what you have done so this is all I can do.
I have an issue where when I append to a file, a newline is always added for some reason. This breaks my code. It is meant to be some sort of login system. I have searched for answers alot. Currently I have found the .rstrip('\r'), .strip('\t') and .strip('\n') have not worked.
Example:
I write to a file like this when it already has the contents password1,username1<>:
print("Create")
with open('database.txt', 'a') as database:
username = input("Enter a username: ")
password = input("Enter a password: ")
combined = (password + "," + username + "<>")
combined = combined.strip('\n')
combined = combined.strip('')
combined = combined.strip(' ')
combined = combined.rstrip('\r')
combined = combined.strip('\t')
database.write(combined)
database.close()
#checking total number of users
with open('usernum.txt', 'r+') as usernum:
#the current number + 1 will be the number of the new user
total_num_of_users = usernum.read()
total_num_of_users = int(total_num_of_users) + 1
#incrementing for future numbers
total_num_of_users = str(total_num_of_users)
usernum.truncate(0)
usernum.write(total_num_of_users)
usernum.close()
#making a file containing the users place/number
namefile = str(username) + '.txt'
with open(namefile, 'w+') as usernum:
usernum.write(total_num_of_users)
usernum.close()
Please ignore the fact that the file is called database.txt lol. If my input is username2 and password2 my expected output is:
password1,username1<>password2,username2<>
However instead I get:
password1,username1<>
password2,username2<>
Can anyone help me wth this? Thanks in advance
I am trying to make a username and password that gets taken from a text file. The username and password is added at the beginning and used after. I add a username and password at the start and it works. It adds it to the text document but it says that it isn't on the document when i enter the 2 previously created credentials. I put the part i belive is giving issues in **. Any way to make this work properly? If my point isn't clear i can specify more if necessary. Thanks.
import time
import sys
text1 = input("\n Write username ")
text2 = input("\n Write password ")
saveFile = open('usernames+passwords', 'r+')
saveFile.write('\n' + text1 + '\n' + text2 + '\n')
uap = saveFile.read()
saveFile.close()
max_attempts = 3
attempts = 0
while True:
print("Username")
username = input("")
print("Password")
password = input("")
*if username in uap and password in uap:
print("Access Granted")*
else:
attempts+=1
if attempts >= max_attempts:
print(f"reached max attempts of {attempts} ")
sys.exit()
print("Try Again (10 sec)")
time.sleep(10)
continue
break
saveFile.write writes to the end of the file, so the file cursor points to the end of the file.
saveFile.read() reads from the current position to the end (docs).
You need to move the file cursor to the beginning of the file, before reading:
text1 = 'foo'
text2 = 'bar'
saveFile = open('/tmp/usernames+passwords', 'r+')
saveFile.write('\n' + text1 + '\n' + text2 + '\n')
saveFile.seek(0)
uap = saveFile.read()
print(uap)
Out:
foo
bar
I tried to make a quick python dictionary bruteforcer to bruteforce a zip file. Although it stops bruteforcing at 26 words for some reason??
CODE:
# Author: drk
# A quick zipfile brute forcer (dictionary)
import zipfile
from tqdm import tqdm
wordlist = "/home/drk/Desktop/list.txt"
zip_file = "/home/drk/Desktop/impossible-password.zip"
file = zipfile.ZipFile(zip_file)
count = input("\nDo you want to count the amount of words? (y/n): ")
if count == "y":
total = len(list(open(wordlist, 'rb')))
print("\nTotal words is: " + str(total))
elif count == "n":
print("ok")
else:
print("did not recognize input, continuing...")
with open(wordlist, "rb") as list:
for word in tqdm(wordlist, total=total, unit="words"):
try:
file.extractall(pwd=word.strip())
except:
continue
else:
print("[+] Password Found!: " + word.decode().strip())
print("[-] None of the passwords did work. ")
OUTPUT:
Do you want to count the amount of words? (y/n): y
Total words is: 100000
0%| | 26/100000 [00:00<00:05, 18968.85words/s]
[-] None of the passwords did work.
Does anyone know why?
You are iterating the string wordlist, which is 26 characters long. It seems like what you want to do is iterate the lines of the file, which you have opened as list. Replace your tqdm call with
tqdm(list, total=total, unit="words")
I hope the title wasn't too confusing, but you'll see what I meant by that in a bit. In the meantime, some backstory-- I'm working on a function that generates random usernames and passwords and writes them in a text file as username:password for another program that collects the username:password line as:
string = line.split(":")
username = string[0]
pwd = string[1]
Why does this matter? Well, when I run my function:
Code:
# To generate users and passwords for the password file:
"""
Usage: count-- how many accounts to generate
file-- where to dump the accounts
method-- dict is where it loops through words
and chooses random ones as users and passwords,
and brute (not implemented yet) is where it chooses
random characters and strings them together as users
and passwords.
users-- if you want any filled in users, put them in here.
passes-- if you want any filled in passes, put them in here.
"""
def genAccts(count, file, method="dict", users=[], passes=[]):
try:
f = open(file, "w")
if method == "dict":
dictionary = "Dictionary.txt"#input("[*] Dictionary file: ")
d = open(dictionary, "r")
words = d.readlines()
d.close()
accts = []
for b in range(0, count):
global user
global pwd
user = random.choice(words)
pwd = random.choice(words)
if b < len(users)-1:
user = users[b]
if b < len(passes)-1:
pwd = passes[b]
acct = [user, pwd]
accts.append(acct)
print("[+] Successfully generated",count,"accounts")
for acct in accts:
combined = acct[0]+":"+acct[1]
print(combined)
f.write(combined)
f.close()
print("[+] Successfully wrote",count,"accounts in",file+"!")
except Exception as error:
return str(error)
genAccts(50, "brute.txt")
In my password file brute.txt, I get an output like
quainter
:slightest
litany
:purples
reciprocal
:already
delicate
:four
and so I'm wondering why is a \n added after the username?
You can fix this by replacing:
words = d.readlines()
with:
words = [x.strip() for x in d.readlines()]
words = d.readlines()
The above function returns a list which contains each line as an item. Every word will contain \n character at the end. So to get the required output, you have to trim the white space characters for username.
user = random.choice(words).strip()
Above line will solve your issue!
Use this:
def genAccts(count, file, method="dict", users=[], passes=[]):
try:
f = open(file, "w")
if method == "dict":
dictionary = "Dictionary.txt"#input("[*] Dictionary file: ")
d = open(dictionary, "r")
words = d.readlines().strip()
d.close()
accts = []
for b in range(0, count):
global user
global pwd
user = random.choice(words)
pwd = random.choice(words)
if b < len(users)-1:
user = users[b]
if b < len(passes)-1:
pwd = passes[b]
acct = [user, pwd]
accts.append(acct)
print("[+] Successfully generated",count,"accounts")
for acct in accts:
combined = acct[0]+":"+acct[1]
print(combined)
f.write(combined)
f.close()
print("[+] Successfully wrote",count,"accounts in",file+"!")
except Exception as error:
return str(error)
genAccts(50, "brute.txt")