0

I am attempting to create a login script. I have the usernames and passwords in a text file that I want python to read and check through to find usernames and passwords.

The biggest problem I am having is "attaching" the password to a username. I can currently only scan the whole of the document for both but not necessarily attached to each other.

#-------------------------------------------------------------------------------
# Name:        LogIn
# Purpose:      Logging In
#
# Author:      Dark Ariel7
#
# Created:     19/02/2013
# Copyright:   (c) Dark Ariel7 2013
# Licence:     I take no responsability for anything.
#-------------------------------------------------------------------------------
from getpass import getpass
from time import sleep
Database = open("C:\\Users\Dark Ariel7\\Desktop\\USB BAckup\\Scripts\\Database.txt", encoding='utf-8')
Username = ("")
Password = ()
def LogIn():
    Database = open("C:\\Users\Dark Ariel7\\Desktop\\USB BAckup\\Scripts\\Database.txt", encoding='utf-8')
    Data = (Database.read())
    Username = ("")
    Password = ()
    Username = input("Username: ")
    Password = getpass(str("Password: "))
    LogIn= ",".join((Username,Password))
    if LogIn in Data:
        print("Welcome, " + Username)
        sleep(3)
        pass
    else:
        print("Failed, Sucker!")
        sleep(5)
        exit()

LogIn()

If you guys could help me figure out what exactly .join part is for that would be great. Should i make a dictionary and use the index for a login sheet? I also want some general feedback on how to make the code better.

This is the txt file that it will be reading:

[Dark Ariel7,123456]
[Poop,Anko]

*Edit Sorry guys I forgot to mention that I am using python 3 not 2. Thanks so far. Very quick replies. Also after the last else instead of exit what do I put so that the function loops until I get the right username password combo?

Dark Ariel7
  • 39
  • 1
  • 8

2 Answers2

0

The basic problem you have is that your file has [ ] surrounding the username and password combination, but you fail to account for this.

There are some other stylistic issues with your code, here is an edited version:

import getpass
from time import sleep

password_file = r'C:\....\Database.txt'

def login(user,passwd):
   ''' Checks the credentials of a user '''
   with open(password_file) as f:
      for line in f:
          if line.strip(): # skips blank lines
              username,password = line.split(',') # this gets the individual parts
              username = username[1:] # gets rid of the [
              password = password[:-1] # the same for the password
              if user == username and password == passwd:
                  return True
   return False

if __name__ == '__main__':
    username = input('Please enter the username: ')
    passwd = getpass('Please enter the password: ')
    if login(user,passwd):
       print('Welcome {1}'.format(user))
       sleep(3)
    else:
       print('Failed! Mwahahaha!!')
       sleep(5)

To start off with, you don't need () to "initialize" variables; more to the point in Python you don't need to initialize variables at all. This is because Python doesn't have variables; but rather names that point to things.

Next, the python style guide says that variable names should be lowercase, along with method names.

Now - the main part of the code:

>>> username, password = '[username,sekret]'.split(',')
>>> username
'[username'
>>> password
'sekret]'

I used split() to break up the line into the username and password parts; but as you see there is still the [ messing things up. Next I did this:

>>> username[1:]
'username'
>>> password[:-1]
'sekret'

This uses the slice notation to strip of the leading and ending characters, getting rid of the [ ].

These lines:

   with open(password_file) as f: # 1
      for line in f: # 2
          if line.strip(): # skips blank lines

Do the following:

  1. Opens the file and assigns it to the variable f (see more on the with statement)

  2. This for loop steps through each line in f and assigns the name line to each line from the file.

  3. The third part makes sure we skip blank lines. strip() will remove all non-printable characters; so if there are no characters left, the line is blank and will have a 0 length. Since if loops only work when the condition is true, and 0 is a false value - in effect what happens is we only operate on non-blank lines.

The final part of the code is another if statement. This is a check to make sure that the file will run when you execute it from the command prompt.

Community
  • 1
  • 1
Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
0

The ".join" part joins the username and password that the user types in with a comma between them (i.e. Poop,Anko) because that's the format in which it's stored in the database, so you can search for it that way.

Here's your code, edited up a bit, with some comments about functionality and style.

from getpass import getpass
from time import sleep
Database = open("C:\\Users\Dark Ariel7\\Desktop\\USB BAckup\\Scripts\\Database.txt", encoding='utf-8')
# These next two lines aren't necessary - these variables are never used; you may want to read up about namespaces:  http://bytebaker.com/2008/07/30/python-namespaces/
#Username = ("")
#Password = ()
def LogIn():
    Database = open("C:\\Users\Dark Ariel7\\Desktop\\USB BAckup\\Scripts\\Database.txt", encoding='utf-8')
#   Removed the parentheses; they have no effect here.  Putting parens around lone statements doesn't have any effect in python.
    Data = Database.read()
#   These next two lines are pointless, because you subsequently overwrite the values you give these variables.  It looks like you're trying to "declare" variables, as you would in Java, but this isn't necessary in python.
#   Username = ("")
#   Password = ()
#   Changed this from "input" to "raw_input" because input does something else that you don't want.
    Username = raw_input("Username: ")
    Password = getpass(str("Password: "))
    LogIn= ",".join((Username,Password))
    if LogIn in Data:
        print("Welcome, " + Username)
#   Not sure why you want the script to sleep, but I assume you have your reasons?
        sleep(3)
#   no need to pass
#       pass
    else:
        print("Failed, Sucker!")
        sleep(5)
#   exit() isn't necessary - the function will end by itself.
#       exit()

LogIn()
Brionius
  • 13,858
  • 3
  • 38
  • 49