Replace a line in a text file using python - 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()

Related

How do I select certain lines in a text file from python script?

So I'm making a python script where you can create an account and that account is saved in a text file. When you try to log in, it will look in the text file for your username and then move down a line for the password but I don't know how to move down a line after finding the username. Any help would be appreciated. :)
Update -
import time
import sys
print ("Do you have an account?")
account = input()
if account == "Yes":
print ("Enter your username")
enterUsername = input()
with open ("Allusers.txt") as f:
if enterUsername in f.read():
print ("Enter your password")
enterpassword = input()
if enterpassword in f.read():
print ("Logged in")
if enterpassword not in f.read():
print ("Wrong password")
if account == "No":
print ("Create a username")
createUsername = input()
with open ("Allusers.txt") as f:
if createUsername in f.read():
print ("Username already taken")
sys.exit()
if createUsername not in f.read():
print ("Create a password")
createPassword = input()
with open ("Allusers.txt") as f:
if createPassword in f.read():
print ("Password not available")
sys.exit()
if createPassword not in f.read():
file_object = open ('Allusers.txt', 'a')
file_object.write("" + createUsername + "\n")
file_object.close()
file_object = open ('Allusers.txt', 'a')
file_object.write("" + createPassword + "\n")
file_object.close()
print ("Done")
This is still work in progress and most likely still has errors here and there.
Assumin that your file look like this:
Adam
password
John
12345678
Horacy
abcdefg
Romek
pass1234
You can try this example:
user = "Horacy"
password = "abcdefg"
with open( "users.txt", "r" ) as file:
for line in file:
if user == line.strip():
if password == file.readline().strip():
print( "Correct" )
break
As stated if someones password equals someones username iterating over all lines and checking may return faulty results you'll want to check only usernames as you iterate, so zipping every other line you can check the username only and return the password:
def get_password(file, username):
with open(file, "r") as f:
data = f.readlines()
for user, pw in zip(data[::2], data[1::2]):
if user.strip() == username:
return pw.strip()
def get_password(file, username):
lines = open(file, "r").readlines() # get the lines from the file
for i, line in enumerate(lines):
if line == username: # if the current is the username, return the following line
return lines[i + 1]
You should only search in usernames. The data[::2] will select usernames.
with open("filename", "r") as f:
data = f.read().splitlines()
email = "email#email"
if email in data[::2]:
id_email=data[::2].index(email)
row=id_email*2-1
password=data[row+1]

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

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)

Python login script using dictionary

I am making a login script for python and it will create passwords and write them to a text file like (username:password). But I want to add a login script that will check to see if the username and password is in the text file.
def reg():
print('Creating new text file')
name = input('Username: ')
passwrd = input('Password: ')
with open("users.txt", "r+") as f:
old = f.read()
f.seek(0)
f.write(name + ":" + passwrd + "\n" + old)
f.close()
def login():
user = input("username: ")
passwrd = input("password: ")
with open('users.txt') as f:
credentials = [x.strip().split(':') for x in f.readlines()]
for user,passwrd in credentials:
(This is where i want to add the code)
reg()
login()
I think it would be something like.
for user,passwrd in credentials:
print("found")
else:
print("not found")
If you make credentials a dict, then you can do:
if user in credentials and credentials[user] == password:
//success
else:
//failure
This should work for making credentials be a dict
with open('users.txt') as f:
credentials = dict([x.strip().split(':') for x in f.readlines()])
You just check to see if they match. Note that you need to make the variable names different:
for user2,passwrd2 in credentials:
if (user == user2 and passwrd == passwrd2):
print ("Passed")

Python, How to replace a complete line which contents a string text?

I have a text file which contents the credentials to access a my app, example off my text file
#cat /etc/app/paswords
petter#domain.com $8324dhedberhnnhdbcdhgvged
userhappy#domain.com $2349cmjedcnecbcdfrfrrf8839
the spaces are tab's
I want to change the password hash or the complete line whith a new password
I have the following code:
#cat passreplace.py
domain = "midomain.com"
user = "userhappy"
email = user + "#" + domain
print email
if email in open('/etc/app/passwords').read():
print "User already exist!! one moment change your password"
#code to remplace password
thank you
fileinput is a good choice for this one.
import fileinput
email = username + password
for line in fileinput.input('/etc/app/passwords', inplace=True):
if email in line:
print("User already exists! Change password now!")
username,password = line.split('\t')
old_pass = input("Enter old password: ")
if old_pass != password:
# do something
new_pass = input("Enter new password: ")
confirm = input("Confirm new password: ")
if new_pass != confirm:
# do something
print("\t".join([email, new_pass]), end="")
else:
print(line, end="")

Python read Router IP from file and telnet into

I would like to read a router IP from a text file, then telnet into it:
import sys
import telnetlib
f = open("C:\\MyIP.txt","r")
line = f.readline()
user = "username"
password = "password"
for line in f:
tn = telnetlib.Telnet(line)
tn.read_until("Login: ")
tn.write(user + "\n")
if password:
tn.read_until("Password: ")
tn.write(password + "\n")
f.close()
However, in the above code, if I try to read it directly from a file, it's not working.
Only like this:
import getpass
import sys
import telnetlib
hostserver = "192.168.2.1"
newline = "\n"
username = "username" + newline
password = "password" + newline
telnet = telnetlib.Telnet(hostserver)
telnet.read_until("Login: ")
telnet.write(username+ "\n")
telnet.read_until("Password: ")
telnet.write(password+ "\n")
while 1:
command = raw_input("> ")
telnet.write(command+ "\n")
if command == "exit":
break
telnet.read_all()
Any help is appreciated
You have the statement
line = f.readline()
and then later, you have:
for line in f:
The for loop will loop over each line of the file that has not already been read. It doesn't really look like you want to loop at all. Remove the for statement since your line variable has already been set above.

Categories

Resources