How can i add the functions try/except in this code? - python

I'm still creating this code where via a dictionary attack i find a password, inserted by the user. However I would insert some controls in the input of the file's source (ex. when I type the source of a file that doesn't exist) and when I open a file but inside there isn't a word that match with the password typed by the user. My mind tell me that I can use istructions as "If, Else, Elif" but other programmers tell me that i could use the try except instructions.
This is the code:
"""
This Code takes as input a password entered by the user and attempts a dictionary attack on the password.
"""
def dictionary_attack(pass_to_be_hacked, source_file):
try:
txt_file = open(source_file , "r")
for line in txt_file:
new_line = line.strip('\n')
if new_line == pass_to_be_hacked:
print "\nThe password that you typed is : " + new_line + "\n"
except(
print "Please, type a password: "
password_target = raw_input()
print "\nGood, now type the source of the file containing the words used for the attack: "
source_file = raw_input("\n")
dictionary_attack(password_target, source_file)

You can put this as your "File does not exist" exception and after you open the existing file you can but an if statement to check if anything exist inside the file in your way:
"""
This Code takes as input a password entered by the user and attempts a dictionary attack on the password.
"""
def dictionary_attack(pass_to_be_hacked, source_file):
try:
txt_file = open(source_file , "r")
if os.stat( txt_file).st_size > 0: #check if file is empty
for line in txt_file:
new_line = line.strip('\n')
if new_line == pass_to_be_hacked:
print("\nThe password that you typed is : " + new_line + "\n")
else:
print "Empty file!"
except IOError:
print "Error: File not found!"
print "Please, type a password: "
password_target = raw_input()
print "\nGood, now type the source of the file containing the words used for the attack: "
source_file = raw_input("\n")
dictionary_attack(password_target, source_file)

Related

Replace a line in a text file using python

I want to replace some of the contents of my file. I have this code:
username= input("enter your new username")
password= input("enter the new password")
file = open("testfile.txt", "r")
replaced_content = ""
for line in file:
line = line.strip()
new_line = line.replace("username:", "username: " + username)
replaced_content = replaced_content + new_line + "\n"
file.close()
write_file = open("testfile.txt", "w")
write_file.write(replaced_content)
write_file.close()
Here, testfile.txt contains:
username:
password:
The problem is when I input the replacement text, it's being added rather than replaced. For example, when I enter a username, I want to replace the line "username:" by "username: admin"; but when I run the code repeatedly, it gets added repeatedly, thus:
username: admin admin
password:
If my username is already in the text file I want to replace it with an other one and not adding the new to the other. How can I make this work? (I try to not import packages or other things like that in my code.)
Check if the line equal "username:" and only do the replacement then. In this code it will replace the username: in a line "username: admin" with "username: " + username giving you the extra admin at the end
The issue is that you find a "username:" in the line and replace it with "username: " + username. So if you had a line like "username: admin", it would simply replace the username as asked, and it would become "username: admin admin".
Try changing the
new_line = line.replace("username:", "username: " + username)
to
new_line = "username: " + username if line.count("username:") > 0 else line
Try this (untested, please report of any errors found)v
username= input("enter your new username")
password= input("enter the new password")
new_l=[username, password]
write_file = open("testfile.txt", "r+")
lines=write_file.readlines()
for i,j in zip(lines, new_l):
write_file.write(i.strip('\n')+j)
write_file.write('\n')
write_file.close()

using open() to read file and then using specific lines in if statement python

I'm working on a login system in python atm.
I got so far that I can register a user and create a .txt file with the username and password in two different lines.
textfile
But when it comes to the login system I've run into a problem. I can read the textfile, but when I'm using these two different lines in an if statement using:
try:
#usr is the username given in the login process by the user(the name of the
#created file is always the name of the user)
data = open(usr + ".txt", "r")
l = data.readlines()
#l[0] is reading the first line of code and the iam comparing
#them to the username and password given by the user
if l[0] == usr and l[1] == pss:
print('LOGED IN')
else:
print('WRONG')
except Exception as e:
print('Error reading file')
I am using the latest version of python and I am running on LinuxPopOs
my whole code:
import time
print("LOGIN -> 1")
print("Register -> 2")
print("")
select_ = input("")
if select_ == '2':
print("Username:")
usernamee = input()
print("Password:")
passworde = input()
print("Type ""y"" to register or ""n"" to cancel")
forward = input("")
if forward == 'y':
#creating database
data = open(usernamee + ".txt", "w")
data.write(usernamee + "\n")
data.write(passworde)
data.close()
else:
print('closing...')
time.sleep(2)
exit(0)
elif select_ == '1':
print("LOGIN:")
usr = input("Username:")
pss = input("Password:")
try:
#usr is the username given in the login process by the user
data = open(usr + ".txt", "r")
l = data.readlines()
#l[0] is reading the first line of code and the iam comparing
#them to the username and password given by the user
if l[0] == usr and l[1] == pss:
print('LOGED IN')
else:
print('WRONG')
except Exception as e:
print('Error reading file')
else:
print(select_ + "is not valid")
Thanks
The problem appears to be that white space and/or newline characters aren't being stripped from the strings read by readline. Changing the if statement to strip trailing characters should rectify that, e.g. if l[0].rstrip() == usr and l[1].rstrip() == pss:

Python text file append error

So I was presented with making a program that uses a text file to store passwords to not forget them. The text file is below.(Passwords.txt)
'Application1': ['Username1', 'Password1']
'Application2': ['Username2', 'Password2']
So, to this I would like to add a new line which would be:
'Application3': ['Username3','Password3']
However when I run the following code it tells me an error saying str is not callable. (passwordsappend.py)
hp = open("Passwords.txt","a") #open the file
key = raw_input("Which app: ")
usr = raw_input("Username: ")
psw = raw_input("Password: ") #make variables to add
hp.write('\n\''(key)'\': ''[\''(usr)'\', ' '\''(psw)'\'],') #make it so that it's like the rest of the file
hp.close() #close the file
I was trying to study python codes to learn how to, but I can't see the problem... Can anyone give me advice?
As said in a different answer the problem is your string handling when writing to the file. I would recommend to use string formatting:
hp.write("\n'%s': ['%s', '%s']" % (key, usr, psw))
See https://pyformat.info/
Recommended code:
# Ask for variables to add
key = raw_input("Which app: ")
usr = raw_input("Username: ")
psw = raw_input("Password: ")
# Open file
with open("Passwords.txt", "a") as hp:
# Add line with same format as the rest of lines
hp.write("\n'%s': ['%s', '%s']" % (key, usr, psw))
If you use the with open(...) as ...: you don't have to call the close method, it's called automatically when you exit the with's scope.
Your problem is when you try to write to the file. Change it to
hp.write('\n\'' + key + '\': ''[\'' + usr + '\', ' '\'' + psw +'\']')

'NameError 'test' not defined. where am I going wrong?

I am using Python 2.7 and am trying to get my program to check if a file exists and if it does, the program should then ask the user if they want to overwrite it. If the file is not there, a new one should be created. These two steps are repeated where the file is found to be existing. Here is the code:
import os.path
file_name = input("Please enter the name of the file to save your data to: Example: test.txt ")
file_open = open(file_name, "w")
if os.path.isfile(file_name):
print ("File exists")
decide = input("Do you want to overwrite the file?, Yes or No")
control = True
while control:
if decide != "Yes":
file_name = input("Please enter the name of the file to save your data to: Example: test.txt ")
if os.path.isfile(file_name):
print ("File exists")
else:
newFile = open(file_name, "w")
newFile.write(str(model))
newFile.close()
control=False
else:
print("Creating a new file..................")
file_open.write(str(model))
file_open.close()
In lines 2, 6 and 10 it should be raw_input() as you are reading string, and check indentation of code.

Weird characters and deficiency of the attribute. Python

I've created a function and got stuck on it.
Meaning of the function:
User types in a file, number and own name.
Program writes the name at the end of the file 'number' times.
And just prints out contents of the file.
What's the problem?
There are strange characters and a big space under it when program reads the file.
Like this: ਍圀漀爀氀搀眀椀搀攀㬀 ㈀  㐀 ⴀ 瀀爀攀猀攀渀琀ഀഀ (and then there is a huge space for 10-15 lines in Powershell)
Error: 'str' object has no attribute 'close'.
def filemania():
print "Great! This way is called \"Filemania\""
file_name = raw_input("Type in any text file> ")
enter_1 = int(raw_input("Enter an integer> "))
enter_2 = raw_input("Enter your name> ")
print "Now your name will apear in the file %d times at the end" % enter_1
open_file = open(file_name, 'a+')
listok = []
while len(listok) < enter_1:
open_file.write(enter_2 + " ")
listok.append(enter_2)
print "Contains of the file:"
read_file = open_file.read()
print read_file
file_name.close()
filemania()
I think the problem is somewhere here:
open_file = open(file_name, 'a+')
Does somebody know how to solve these problems?
Firstly you set file_name = raw_input("Type in any text file> ") so you are trying to close a string with file_name.close():
When you write to open_file you move the pointer to the end of the file because you are appending so read_file = open_file.read() is not going to do what you think.
You will need to seek to the start of the file again to print the content, open_file.seek(0).
def filemania():
print "Great! This way is called \"Filemania\""
file_name = raw_input("Type in any text file> ")
enter_1 = int(raw_input("Enter an integer> "))
enter_2 = raw_input("Enter your name> ")
print "Now your name will apear in the file %d times at the end" % enter_1
# with automatically closes your files
with open(file_name, 'a+') as open_file:
listok = []
# use range
for _ in range(enter_1):
open_file.write(enter_2 + " ")
listok.append(enter_2)
print "Contains of the file:"
# move pointer to start of the file again
open_file.seek(0)
read_file = open_file.read()
print read_file
filemania()
For your second error, you are trying to close file_name, which is the raw input string. You mean to close open_file
Try that and report back.

Categories

Resources