Python read Router IP from file and telnet into - python

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.

Related

read username and password from text file

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

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()

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]

Python: How can i search for a whole word in a .txt file?

ive been searching for ages for a solution on my problem:
When a user types in a name, which is already saved in a .txt file, it should print "true".
If the username is not already existing it should add the name, the user typed in.
The Problem is, that it even prints out true when the typed name is "Julia", but "Julian" is already in the list. I hope you get my point.
I already read maaany solutions here on stackoverflow but nothing worked for me when working with a .txt file
My code:
import mmap
username = input("username: ")
names_file = open("names_file.txt", "a")
paste = bytes(username, 'utf-8')
with open("names_file.txt", "rb", 0) as file, \
mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_READ) as s:
if s.find(paste) != -1:
print("true")
else:
names_file.write("\n" + username)
print(username + " got added to the list")
names_file.close()
username = input("username: ")
found = False
with open("names_file.txt", "r") as file:
for line in file:
if line.rstrip() == username:
print("true")
found = True
break
if not found:
with open("names_file.txt", "a") as file:
file.write( username + "\n")
print(username + " got added to the list")
You could add the newline after the name and search for the name with the newline character:
import mmap
username = input("username: ")
names_file = open("names_file.txt", "a")
paste = bytes('\n' + username + '\n', 'utf-8')
with open("names_file.txt", "rb", 0) as file, \
mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_READ) as s:
if s.find(paste) != -1:
print("true")
else:
names_file.write('\n' + username + '\n')
print(username + " got added to the list")
names_file.close()
This will not work for names with spaces inside -- for such cases you'll have to define different separator (also if all names begin with a capital letter and there are no capital letters in the middle of the name then you could spare the newline before the name)
Try this i have updated my answer.
import mmap
import re
status = False
username = input("username: ")
names_file = open("names_file.txt", "a")
paste = bytes(username, 'utf-8')
with open("names_file.txt", "rb", 0) as file, \
mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_READ) as s:
for f in file:
f = f.strip()
if f == paste:
print("true")
status = True
if status == False:
names_file.write("\n" + username)
print(username + " got added to the list")
names_file.close()

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 +'\']')

Categories

Resources