Can't make log in in Python 3.x - python

I have created a database and needs to check that one for corresponding user name and password... if it is there it should print "success" else not...
I tried many ways, it will print only if the there is a correct username and password... else it shows nothing.
It does not show can't log in or error. It only exits with 0 error without any display.
#!/usr/bin/python
import pymysql
# Open database connection
db = pymysql.connect("localhost","root","","text" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
eg = input("What's your user name? ")
password = input("What's your user password? ")
sql = ("SELECT * FROM login WHERE name = '%s' AND password= '%s' " % (eg,password))
try:
# Execute the SQL command
cursor.execute(sql)
results = None
# Fetch all the rows in a list of lists.
results = cursor.fetchall()
try:
if results is not None:
for row in results:
id = row[0]
name = row[1]
password = row[2]
print("login success")
except:
print("Error you arenot in the planet dude sign up first")
except:
print("Error you arenot in the planet dude sign up first")
# disconnect from server
db.close()

Something seems off with the indentation, try the following segment:
try:
# Execute the SQL command
cursor.execute(sql)
results = None
# Fetch all the rows in a list of lists.
results = cursor.fetchall()
try:
if results is not None :
for row in results:
id = row[0]
name = row[1]
password= row[2]
print ("login success")
except:
print("Error you arenot in the planet dude sign up first")
except:
print ("Error you are not in the planet dude sign up first")

for row in results:
id = row[0]
name = row[1]
password= row[2]
print ("login success")
Should be
success = False
for row in results:
db_id = row[0]
db_name = row[1]
db_password= row[2]
if db_name == eg and db_password == password:
success = True
print ("login success")
The variables created from row[1] and row[2] need to be different from the eq and password variables created above. Once that is done, you just need to compare them to see if they match up.
You can check the success variable later on to perform an action only if the login process was successful or not successful.

Related

login system connected with database mysql using easygui in raspberry pi 3

I'm beginning using GUI . My first project is to do login system that connected to database mysql using easygui in raspberry pi 3. I already do the coding for enter the password but I dont know how to connect it with database while press ok button. While I run the coding, it will be display the password and username at the cmd. I dont know how to set it with database.
This is my coding:
import easygui as eg
msg = "Enter logon information"
title = "Demo of multpasswordbox"
fieldNames = ["User ID", "Password"]
fieldValues = [] # we start with blanks for the values
fieldValues = eg.multpasswordbox(msg,title, fieldNames)
# make sure that none of the fields was left blank
while 1:
if fieldValues == None: break
errmsg = ""
for i in range(len(fieldNames)):
if fieldValues[i].strip() == "":
errmsg = errmsg + ('"%s" is a required field.\n\n' % fieldNames[i])
if errmsg == "": break # no problems found
fieldValues = multpasswordbox(errmsg, title, fieldNames, fieldValues)
print "Reply was:", fieldValues
You're creating FieldValues as an empty list that will store your inputs. Inputs are stored in the order of your created fields, in your code:
import easygui as eg
msg = "Enter logon information"
title = "Demo of multpasswordbox"
fieldNames = ["User ID", "Password"]
fieldValues = [] # we start with blanks for the values
fieldValues = eg.multpasswordbox(msg,title, fieldNames)
userID = fieldValues[0]
password = fieldValues[1]
from easygui import *
import mysql.connector
TITLE = "Enter logon information"
conn = ""
table = ""
def Login():
global conn
conn = mysql.connector.connect(host='localhost',user='pi',password='1234',db='mydb')
cursor = conn.cursor()
msg = "Enter logon information"
title = "Login"
fieldNames = ["Usercode","Password"]
fieldValues = []
fieldValues = multpasswordbox(msg,title,fieldNames)
usercode, password = fieldValues[0], fieldValues[1]
sql = "SELECT * FROM `data` WHERE usercode = %s AND password = %s"
cursor.execute(sql,(usercode,password))
results = cursor.fetchall()
Login()

how to read a variable line by line from a text file and split it python

i'm trying to create a sign up menu where it takes your username and password then saves them onto a new line in a text text file so after making multiple accounts ill have multiple lines with one username and one password each. i then want to read the file back line by line and split the username and password into two variables (u and p), save u and p onto a database in sqlite3 then repeat for the next line until all lines have been saved to the database. however i cannot figure this out as no matter what i try there's an error with unpacking values either to many or to few. i think the \n at the end of each line may be the/one of the problems.
any help is appreciated thanks.
Here is the code:
import time
import sqlite3
import os
db2 = sqlite3.connect('pass.db')
cur = db2.cursor()
def sign_up():
global cur
details = '1'
with open('username','a') as user:
cur.execute('CREATE TABLE IF NOT EXISTS pass (username TEXT, password TEXT)')
username = input('please enter a username:')
username = username.title()
password = ''
password2 = '.'
while password != password2 or len(password) < 6 or password.isalnum() == False:
password = input('please enter a password with AT LEAST 6 CHARACTERS AND ONE NUMBER:')
password2 = input('please confirm your password:')
user.write(username + ',' + password + ',' + '\n')
with open('username','r') as user:
hello = ''.join(user.readlines())
print (hello)
for line in hello:
details = user.readline()
details = ''.join(details)
print (details)
u, p = details.split(',')
cur.execute('INSERT INTO pass (username, password) VALUES (?, ?)',(u, p,))
print(u)
print(p)
cur.execute('SELECT username FROM pass WHERE username = ?',(username,))
for row in cur:
print(row)
sign_up()
replace details = ''.join(details) code with follwing
details = details.strip()
if details != '':
u, p = details.split(',')
cur.execute('INSERT INTO pass (username, password) VALUES (?, ?)',(u., p,))
use strip() or lstrip() function which will remove '\n'
The problem is that you are joining the lines in hello. When you iterate, you are iterating the characters in a string, and of course you cannnot split a character.
thanks guys i know this is by no means the best way to store passwords or anything but for what its used for and i have looked on google to try and find something better but everything that came up was either far to basic or at a level i dont yet understand and the actual security of the password isnt too important for what im using them for.
i got it too work with this code:
import time
import sqlite3
import os
db2 = sqlite3.connect('pass.db')
cur = db2.cursor()
def sign_up():
global cur
details = '1'
with open('username','a') as user:
cur.execute('CREATE TABLE IF NOT EXISTS pass (username TEXT, password TEXT)')
username = input('please enter a username:')
username = username.title()
password = ''
password2 = '.'
while password != password2 or len(password) < 6 or password.isalnum() == False:
password = input('please enter a password with AT LEAST 6 CHARACTERS AND ONE NUMBER:')
password2 = input('please confirm your password:')
user.write(username + ',' + password + ',' + '\n')
with open('username','r') as user:
details = user.readline()
details = details.strip()
print(details)
while details != '':
if details != '':
u, p = details.split(',',1)
cur.execute('INSERT INTO pass (username, password) VALUES (?, ?)',(u, p,))
details = user.readline()
details = details.strip()
cur.execute('SELECT * FROM pass')
for row in cur:
print(row)
cur.execute('SELECT username FROM pass WHERE username = ?',(username,))
data = cur.fetchall()
if len(data) == 0:
sign_up()
sign_up()

bypass known exception of mysql in python

I am trying to bypass "Cannot delete or update a parent row: a foreign key constraint fails" inside my python script.
So I am planning to drop all tables but this error throws up due to inter relationship.
My query is I need to get this automated and i know I am gonna come with the same error, but I know how to bypass it by calling SET FOREIGN_KEY_CHECKS=0; and then once deleted enable the feature again SET FOREIGN_KEY_CHECKS=1;.
Need to know how to automate this inside python
import MySQLdb
import sys
if len(sys.argv) != 4:
print "please enter the Hostname to connect followed by:"
print "mysql username;"
print "mysql db to connect;"
else:
_host = sys.argv[1]
_user = sys.argv[2]
# _pass = sys.argv[3]
_db = sys.argv[3]
cham = raw_input("please enter the command to be executed:- ")
_pass = raw_input("please enter password:- ")
if cham == "drop table":
db = MySQLdb.connect(host = _host, user = _user,db = _db, passwd = _pass )
cursor = db.cursor()
cursor.execute("show tables")
for i in cursor.fetchall():
cursor.execute("drop table" + " " + (i[0]))
print cursor.fetchall()
print "all the tables has been deleted"
db.close()
else:
db = MySQLdb.connect(host = _host, user = _user,db = _db, passwd = _pass )
cursor = db.cursor()
cursor.execute(cham)
print cursor.fetchall()
db.close()
I tried the following snip and it worked, thanks anyways.
if cham == "drop table":
db = MySQLdb.connect(host = _host, user = _user,db = _db, passwd = _pass )
cursor = db.cursor()
cursor.execute("show tables")
for i in cursor.fetchall():
try:
cursor.execute("drop table" + " " + (i[0]))
#print cursor.fetchall()
except:
cursor.execute("SET FOREIGN_KEY_CHECKS=0")
cursor.execute("drop table" + " " + (i[0]))
cursor.execute("SET FOREIGN_KEY_CHECKS=1")
# print "all the tables has been deleted"
db.close()

sqlite3.OperationalError: database is locked - How to avoid this?

I'm using an open source piece of python code that basically pulls in a location of an entity and saves these details to a DB in real time. lets call it scanner the scanner program. DB file it saves it to is a sqlite file: db.sqlite.
As this is happening my piece of code in question is searching the db file every 45 seconds performing a select statement to find a certain value. This will work a couple of times but after running for a couple of minutes concurrently with the scanner program they run into a DB lock error:
sqlite3.OperationalError: database is locked
So what can I do to my code to ensure this lock does not happen. I cannot change how the scanner program accesses the DB. Only my program.
Any help here would be great. I've seen timeouts mentioned along with threading but I am not sure on either.
from datetime import datetime
import sqlite3
import time
import json
import tweepy
def get_api(cfg):
auth = tweepy.OAuthHandler(cfg['consumer_key'], cfg['consumer_secret'])
auth.set_access_token(cfg['access_token'], cfg['access_token_secret'])
return tweepy.API(auth)
# Fill in the values noted in previous step here
cfg = {
"consumer_key" : "X",
"consumer_secret" : "X",
"access_token" : "X",
"access_token_secret" : "X"
}
with open('locales/pokemon.en.json') as f:
pokemon_names = json.load(f)
currentid = 1
pokemonid = 96 #test
while 1==1:
conn = sqlite3.connect('db.sqlite')
print "Opened database successfully";
print "Scanning DB....";
time.sleep(1)
cur = conn.execute("SELECT * FROM sightings WHERE pokemon_id = ? and id > ?", (pokemonid, currentid))
row = cur.fetchone()
if row is None:
print "No Pokemon Found \n "
time.sleep(1)
while row is not None:
#get pokemon name
name = pokemon_names[str(pokemonid)]
#create expiry time
datestr = datetime.fromtimestamp(row[3])
dateoutput = datestr.strftime("%H:%M:%S")
#create location
location = "https://www.google.com/maps/place/%s,%s" % (row[5], row[6])
#inform user
print "%s found! - Building tweet! \n" % (name)
time.sleep(1)
#create tweet
buildtweet = "a wild %s spawned in #Dublin - It will expire at %s. %s #PokemonGo \n "%(name, dateoutput, location)
#print tweet
#log
print buildtweet
currentid = row[0]
time.sleep(1)
#send tweet
api = get_api(cfg)
tweet = buildtweet
try:
status = api.update_status(status=tweet)
print "sent!"
except:
pass
print "this tweet failed \n"
time.sleep(30)
row = cur.fetchone()
cur.close()
conn.close()
print "Waiting..... \n "
time.sleep(45)
conn.close()

Why is the length of the list displayed as zero in my code?

import ldap
try:
l = ldap.initialize("ldap://ldap.xxxxx.com:389")
username=raw_input("Enter the username : ")
password = raw_input("Enter the password :")
if(username == "" or password==""):
print "Login Error : Username or password can't be blank"
else:
l.simple_bind(username,password)
print "Contact..."
except ldap.LDAPError, e:
print e
baseDn = "ou=active, ou=employees, ou=people, o=xxxxx.com";
searchScope = ldap.SCOPE_ONELEVEL
#retrieve all attributes
retrieveAttributes = None
search_query = raw_input("Enter the query :")
searchFilter = "cn="+search_query
try :
ldap_result_id = l.search(baseDn, searchScope, searchFilter, retrieveAttributes)
result_set = []
while 1:
result_type, result_data = l.result(ldap_result_id, 0)
if(result_data == []):
break
else:
if result_type == ldap.RES_SEARCH_ENTRY:
result_set.append(result_data)
#print result_set
print len(result_set)
except ldap.LDAPError, e:
print e
#print result_set[0]
The above code uses python-ldap to access ldap services. The result_set type is displayed as list but the number of items when using the len() function turns out to be zero. I need to perform operations on the retrieved string.

Categories