How to access the value of username from htpasswd file using python script - python

I have created a username/ password in htpasswd file. In my python script file I would like to access the username value for further processing. How do I achieve that? I am using Linux OS.

The htpasswd format is `:", something that isn't terribly difficult to parse. Simply go through line by line and split on a colon, taking the first value:
usernames = []
with open("passwdfile") as htpwd:
for line in htpwd.readlines():
username, pwd = line.split(":")
usernames.append(username)
Or more consisely:
with open("passwdfile") as htpwd:
usernames = [line.split(":")[0] for line in htpwd.readlines()]

Related

Insert a value before comma in a file

I'm new to Python and I'm trying to create a simple program for login which reads/writes the information to/from a text file, but I'm having an issue.
Let's say I have the following content in a text file:
mytest#gmail.com, testPass123
First the email and after the comma the password. How can I read those two separately?
I have used .split(',') but it stores the whole line.
If I run this:
email = []
for line in file:
email.append(line.split(','))
print(email[0])
I get the following output:
['mytest#gmail.com', ' testPass123\n']
I think your variable naming is confusing you here. If you name email accounts, things might become clearer:
accounts = []
for line in file:
accounts.append(line.strip().split(','))
for email, password in accounts:
print("Email:", email, "Password:", password)
You may be looking for multiple assignment
>>> a, b = "em#ail, pass".split(",")
>>> a
'em#ail'
>>> b
' pass'

Check variable against specific line in a text file | Python 3.6.x

Pretend I am making an email script. The user has already made a username and password, which has been stored in a text file so they can log in later at anytime.
The user needs to be able to log in. I want python to check that the users input matches the information in the text file from earlier, on their corresponding line. Capitalization doesn't matter.
The text file that was created initially reads:
johncitizen
johnspassword
My python script should read something like:
##Reads text file
guessusername = input('What is your username? ')
guesspassword = input('What is your password? ')
if guessusername.lower() = lines[0] and guesspassword = lines[1]:
##Grant access
I don't mind if capitalization is wrong, as long as the string itself matches up
Before first of all, what you are doing with plain text password storage is ill-advised. You should be using hashing+salting, or even better, pick a decent framework to work in and learn from how they do it.
First of all, your data storage format should be more record like:
user_id<tab>username<tab>password
user_id<tab>username<tab>password
user_id<tab>username<tab>password
In that case, you are able to read the file like this:
username = ... #user input
password = ... #user input
found_user_id = None
with open('pass.txt', 'rt') as f:
for line in f:
fields = line.split("\t")
if fields[1] == username and fields[2] == password:
found_user_id = fields[0]
break
#okay, here if found_user_id is not None, then you have found them
#if it is None, then you did not find them.
Truly, a database is much more useful than a text file, but this is how it works!

Python- Reading back usernames and passwords into a program to authenticate

I am currently writing a program in Python that asks if you have a log in. If no, they proceed to create a username and password. If yes, they log in and their details are checked against a text file. The text file looks like this (Username then password):
whitehallj27
EXpass%20
Username2
EXPASSWORD%%%
james_27
password1234
I am trying to figure out a way of programming this as simply as possible. It seems to work, but isn't nearly as simple and doesn't really work how I thought it would. Here is the code snippet:
logins={}
usernames_passwords=open("UsernamesAndPasswords.txt","r")
count=0
for line in usernames_passwords:
count=count+1
count=count/2
usernames_passwords.close()
usernames_passwords=open("UsernamesAndPasswords.txt","r")
try:
for x in range(count):
username=usernames_passwords.readline()
password=usernames_passwords.readline()
logins[username]=password
except TypeError:
count=int(count+0.5)
for x in range(count):
username=usernames_passwords.readline()
password=usernames_passwords.readline()
logins[username]=password
usernames_passwords.close()
print(logins)
Also, how would I go about authenticating the username and password to check it's correct.
Many thanks,
James Duxbury
Assuming that variables user and passwd have the username and password provided by the user, then just read the file in two lines:
file_contents = []
with open("UsernamesAndPasswords.txt","r") as f: #use "with", it will auotamtically close the file
file_contents = f.readlines()
usernames = file_contents[0::2] #step by 2, take all elements starting at index 0
passwords = file_contents[1::2] #step by 2, take all elements starting at index 1
found_at_index = -1
for i in range(0,len(usernames)):
if user == usernames[i] and passwd == passwrods[i]:
found_at_index = i
break
if found_at_index >= 0 :
#do whatever you want, there is match
else:
#I don't know what you wanted to do in this case
Please read this for the with keyword and this for how to read a file nicelly.
Also this about the [::] syntax.
You could create a dictionary with the user names and passwords like this:
dict = {
'user-name': 'password-hashing',
'another-user': 'another-password'
}
after you've done it you can save this dict in a json file, and load its content when the user asks for login.
the docs for handling json files with python: https://docs.python.org/3/library/json.html
obs.: it will look simpler, but its not the best way of doing this king of thing

Username and Password login

I'd like to create a Login in which will open a text/csv file read the "Valid" usernames and passwords from the file and then if whatever the user has added has matched what was in the file then it will allow access to the rest of the program
How would i integrate the code below into one of which opens a file reads valid usernames and passwords and checks it against the users input
Currently i have something which works but there is only one password which i have set in the code.
Password = StringVar()
Username = StringVar()
def EnterPassword():
file = open('Logins.txt', 'w') #Text file i am using
with open('Logins.txt') as file:
data = file.read() #data=current text in text file
UsernameAttempt = Username.get()#how to get value from entry box
PasswordAttempt = Password.get()#how to get value from entry box
if PasswordAttempt == '' and UsernameAttempt == '':
self.delete()
Landlord = LandlordMenu()
else:
PasswordError = messagebox.showerror('Password/Username Entry','Incorrect Username or Password entered.\n Please try again.')
PasswordButton = Button(self.GenericGui,text = 'Landlord Section',height = 3, width = 15, command = EnterPassword, font = ('TkDefaultFont',14),relief=RAISED).place(x=60,y=175)
Some assistance would be appreciated
Please have a look at some documentation. Your question in "Coding Comments" -> #how to get value from entry box is easy to be solved using official documentation.
For reading files there is also official documentation on strings and file operations (reading file line by line into string, using string.split(';') to get arrays instead of row-strings).
Please do read documentation before writing applications. You do not need to know the complete API of all python modules but where to look. It is very exhausting to be dependent on other users / developers when there is no actual need for it (as there is very detailed documentation and tons of howtows for that kind of stuff).
This is not meant to be offensive but to show you how easy you can get documentation. Both results where first-results from a search engine. (ddg)
Please keep in mind that SO is neither a code writing service nor a let-me-google-that-for-you forum.

Automate `svn up` with password entry

I need a script that updates my copy of a repository. When I type "svn up" I usually am forced to enter a password, how do I automate the password entry?
What I've tried:
import pexpect, sys, re
pexpect.run("svn cleanup")
child = pexpect.spawn('svn up')
child.logfile = sys.stdout
child.expect("Enter passphrase for key \'/home/rcompton/.ssh/id_rsa\':")
child.sendline("majorSecurityBreach")
matchanything = re.compile('.*', re.DOTALL)
child.expect(matchanything)
child.close()
But it does not seem to be updating.
edit: If it matters, I can get my repository to update with child.interact()
import pexpect, sys, re
pexpect.run("svn cleanup")
child = pexpect.spawn('svn up')
child.logfile = sys.stdout
i = child.expect("Enter passphrase for key \'/home/rcompton/.ssh/id_rsa\':")
child.interact()
allows me to enter my password and starts updating. However, I end up with an error anyway.
-bash-3.2$ python2.7 exRepUpdate.py
Enter passphrase for key '/home/rcompton/.ssh/id_rsa':
At revision 4386.
At revision 4386.
Traceback (most recent call last):
File "exRepUpdate.py", line 13, in <module>
child.interact()
File "build/bdist.linux-x86_64/egg/pexpect.py", line 1497, in interact
File "build/bdist.linux-x86_64/egg/pexpect.py", line 1525, in __interact_copy
File "build/bdist.linux-x86_64/egg/pexpect.py", line 1515, in __interact_read
OSError: [Errno 5] Input/output error
edit: Alright I found a way around plaintext password entry. An important detail I left out (which, honestly, I didn't think I'd need since this seemed like it would be an easy problem) is that I had to send a public key to our IT dept. when I first got access to the repo. Avoiding the password entry with in the ssh+svn that I'm dealing with can be done with ssh-agent. This link: http://mah.everybody.org/docs/ssh gives an easy overview. The solution Joseph M. Reagle by way of Daniel Starin only requires I enter my password one time ever, on login, allowing me to execute my script each night despite the password entry.
If you don't want to type password many times, but still have a secure solution you can use ssh-agent to keep your key passphrases for a while. If you use your default private key simply type ssh-add and give your passphrase when asked.
More details on ssh-add command usage are here: linux.die.net/man/1/ssh-add
You should really just use ssh with public keys.
In the absence of that, you can simply create a new file in ~/.subversion/auth/svn.simple/ with the contents:
K 8
passtype
V 6
simple
K 999
password
V 7
password_goes_here
K 15
svn:realmstring
V 999
<url> real_identifier
K 8
username
V 999
username_goes_here
END
The 999 numbers are the length of the next line (minus \n). The filename should be the MD5 sum of the realm string.

Categories