Python with Sqlite 3, how to extract only text, without 'u? - python

I have the following code:
password_master = str(self.master_password.text())
username = str(self.comboBox.currentText())
result = c.execute("SELECT * FROM register_table WHERE MASTER = '"+password_master+"' AND USERNAME = '"+username+"'")
if (len(result.fetchall()) > 0):
print("user found")
password_check = c.execute("SELECT PASSWORD FROM register_table WHERE USERNAME = '"+username+"' AND MASTER = '"+password_master+"'").fetchall()
password = str(password_check)
login(username, password)
From the "password_check" query I would like to extract only the text, because I need to pass variable "password" to "login" function.
I tried everything but I always receive the following output:
[(u'#-passwordtest-#',)]
Is there a way to extract simply
passwordtest
Many thanks in advance!!!

First off, I'll start with the standard SQL Injection warning. Granted, this doesn't look like it's web facing, but still. You should be using bind variables.
Secondly, your query will return an array of values, so you're trying to run the str() function on an array that contains strings. I would replace the lines:
password_check = c.execute("SELECT PASSWORD FROM register_table WHERE USERNAME = '"+username+"' AND MASTER = '"+password_master+"'").fetchall()
password = str(password_check)
with:
results = c.execute("SELECT PASSWORD FROM register_table WHERE USERNAME = '"+username+"' AND MASTER = '"+password_master+"'").fetchone()
password = results[0]

Related

How do i get the password from the SQL database without it quoting the output?

My code right now is
import mysql.connector import hashlib
cnx = mysql.connector.connect(user='root', password='!Joshua1',
host='127.0.0.1',
database='passwordhashtest')
cursor = cnx.cursor()
Password = input("Enter the password >>")
hashpass = hashlib.md5(Password.encode('utf8')).hexdigest()
Email=input("number")
passwordcheck='''SELECT b FROM password2 WHERE a = %s AND b = %s'''
values=(Email,hashpass)
cursor.execute(passwordcheck,values)
hashedpassindatabase=cursor.fetchone()
print(hashedpassindatabase)
if hashedpassindatabase==hashpass:
print("Success!") else:
print("error")`
My output comes out as:
('d1133275ee2118be63a577af759fc052',)
error
See my problem is the quotes and the comma!
HOW DO I REMOVE THAT!?!?!??!
It seems impossible, i tried everything i can think of!
hashpass is stored as
d1133275ee2118be63a577af759fc052
If the data im getting from mysql doesnt include the quotes and the comma, then things would get verified pretty easily, but it isnt. THATS WHAT I DONT GET!!!!!!!!! HELP!!!!!!!!!!!!
The return value of a DB API2 compliant cursor.fetchone() is a sequence (or None).
In your case, the result is a tuple with a single item:
t = ('d1133275ee2118be63a577af759fc052',)
To access this item, use t[0].
Or to stick to your variable names:
hashedpassindatabase = ('d1133275ee2118be63a577af759fc052',)
actual_value = hashedpassindatabase[0]
print(actual_value)
Output:
d1133275ee2118be63a577af759fc052

Python-Selenium - Brute force script using nested For loops for username and password list

I am new to Python and am trying to create a brute force script using Python and Selenium to brute force a website using usernames and passwords from a text file. The issue I am facing is that the script takes the first username and runs it against the password list and then it stops.
I have tried iterating in lists, nested for loops and even calling the function with usernames manually presented for testing but still the logic only picks the first user name and then once the password list end is reached the application finishes.
Any help would be highly appreciated.
user_list = open('usernamelist.txt' , 'r') #File containing usernames
pass_list = open('passwordlist.txt' , 'r') #File containing passwords
for usernm in user_list:
drv.get(target-website-url)
for passwd in pass_list:
username = drv.find_element_by_xpath("/html/body/div/ui-view/ui-view/div/div/div/div/div[3]/ui-view/div/form/div[1]/input")
username.send_keys(usernm.split())
password = drv.find_element_by_xpath("/html/body/div/ui-view/ui-view/div/div/div/div/div[3]/ui-view/div/form/div[2]/input")
password.send_keys(passwd.split())
submit = drv.find_element_by_xpath('//*[#id="loginButton"]')
submit.click()
time.sleep(1)
drv.refresh()
#To check for a successful or failed login using the current URL
login_fail = drv.current_url
if "redirect" in login_fail:
print("User" + usernm + " and " + passwd + " combo FAILED")
elif "dashboard" in login_fail:
print("User" + usernm + " and " + passwd + " combo SUCCEEDED")
drv.refresh()
time.sleep(2)
I would suggest using zip function, that returns an iterator out of those two lists:
username = drv.find_element_by_xpath('/html/body/div/ui-view/uiview/div/div/div/div/div[3]/ui-view/div/form/div[1]/input')
password = drv.find_element_by_xpath('/html/body/div/ui-view/ui-view/div/div/div/div/div[3]/ui-view/div/form/div[2]/input')
for user user_list:
for passw in pass_list:
username.send_keys(user.strip()) # .strip() for removing \r and \n
password.send_keys(passw.strip()) # .strip() for removing \r and \n
submit = drv.find_element_by_xpath('//*[#id="loginButton"]')
submit.click()
time.sleep(2)
login_fail = drv.find_element_by_class_name("appInfoBox__header")
login_failure = (login_fail.get_attribute("innerHTML"))
if "Login error" in login_failure:
print("{user} and {passw} combo FAILED").format(
user = user,
passw = passw
)
else:
print("{user} and {passw} combo SUCCEEDED").format(
user = user,
passw = passw
)
drv.refresh()
time.sleep(2)
Because in your case the code iterates over all of the usernames sends them to the specified element and then iterates over password and sends them to the other element, that is why it shows as in one line:
for usernm in user_list:
username = drv.find_element_by_xpath('xpath')
username.send_keys(usernm)
for passwd in pass_list:
password = drv.find_element_by_xpath('xpath')
password.send_keys(passwd)

Can I select just one specific element in a sql query(select statement)?

I am trying to create a command line tool that generates a random string(password) of a given length, stores it in a sql db, and can be queried by name. The password generation and storing of it's output by a given name works beautifully, but trying to select only the password element is giving me trouble. I was able to select all from the table but that returns the name and the password. I only want the password returned. I thought about just splicing the output or even using the linux cut command, but I'd rather just get it from the select statement. Is this possible? My current SELECT statement returns: operation parameter must be a str. When I try it without the call to (name) at the end of the SELECT statement like this: query_password = """SELECT * FROM password_table WHERE name = ?"""
I get this error:
File "passbox.py", line 44, in <module>
query_pswd_by_name(name)
File "passbox.py", line 39, in query_pswd_by_name
c.execute(query_password)
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 0 supplied.
BTW I'm sure my query_pswd_by_name function is all wrong, I've been experimenting. When I just create a connection and SELECT statement outside of a function it does return the name and password.
Also note that I've disguised my database file's name with asterisks for the purpose of this post. I am using an actual working db file in practice.
Here is all the code I've written so far:
import secrets
import string
import sqlite3
#CREATE PASSWORD OF GIVEN LENGTH
def get_pass(length):
return "".join(secrets.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits + string.punctuation) for x in range(length))
length = int(input("Enter the length of password: "))
password= get_pass(length)
print(password)
name = str(input("Enter name for password: "))
#CREATE DATABASE CONNECTION
conn = sqlite3.connect("****.db")
#CREATE CURSOR OBJECT
c = conn.cursor()
#CREATE TABLE IN DISK FILE BASED DATABASE
c.execute("""CREATE TABLE IF NOT EXISTS password_table (
name TEXT,
pswd TEXT
)""")
c.execute("INSERT INTO password_table (name, pswd) VALUES (?, ?)", (name, password))
#COMMIT CHANGES
conn.commit()
conn.close()
def query_pswd_by_name(name):
conn = sqlite3.connect('****.db')
c = conn.cursor()
query_password = """SELECT * FROM password_table WHERE name = ?""", (name)
c.execute(query_password)
result = c.fetchall()
for row in result:
print(row[1])
conn.commit()
query_pswd_by_name(name)
#CLOSE CONNECTION
conn.close()```
You need to break up the argument to the execute call.
c.execute(*query_password)
Or
c.execute("""SELECT * FROM password_table WHERE name = ?""", (name))

Error when splitting string into two variables in python

I need to be able to input a users full name in an entry box and then have it split into a firstname and surname variable, so that these variables can be used to search a database for. However, I'm having issues with this, as it is something I haven't really done before. Any help is appreciated.
studentname = (StudName.get())
conn = sqlite3.connect('MyComputerScience.db')
c = conn.cursor()
firstName, lastName = studentname.split()
namesearchadd = (firstname, lastname,)
c.execute ("SELECT * FROM users WHERE FName = ? and SName= ? VALUES (?,?);", (namesearchadd,))
data = c.fetchall()
if len(data) == 0:
print ("whoops")
else:
Label(screen6, text = "Success", fg="GREEN").place(relx=0.101, rely=0.725, height=21, width=194)
firstName, lastName = studentname.split()
ValueError: not enough values to unpack (expected 2, got 0)

how to make text clickable in python

How to make text clickable ?
class ComplainceServer():
def __init__(self, jira_server, username, password, encoding='utf-8'):
if jira_server is None:
error('No server provided.')
#print(jira_server)
self.jira_server = jira_server
self.username = username
self.password = password
self.encoding = encoding
def checkComplaince(self, appid, toAddress):
query = "/rest/api/2/search?jql=issuetype = \"Application Security\" AND \"Prod Due Date\" < now()
request = self._createRequest()
response = request.get(query, contentType='application/json')
# Parse result
if response.status == 200 and action == "warn":
data = Json.loads(response.response)
print "#### Issues found"
issues = {}
msg = "WARNING: The below tickets are non-complaint in fortify, please fix them or raise exception.\n"
issue1 = data['issues'][0]['key']
for item in data['issues']:
issue = item['key']
issues[issue] = item['fields']['summary']
print u"* {0} - {1}".format(self._link(issue), item['fields']['summary'])
print "\n"
data = u" {0} - {1}".format(self._link(issue), item['fields']['summary'])
msg += '\n'+ data
SOCKET_TIMEOUT = 30000 # 30s
email = SimpleEmail()
email.setHostName('smtp.com')
email.setSmtpPort(25)
email.setSocketConnectionTimeout(SOCKET_TIMEOUT);
email.setSocketTimeout(SOCKET_TIMEOUT);
email.setFrom('R#group.com')
for toAddress in toAddress.split(','):
email.addTo(toAddress)
email.setSubject('complaince report')
email.addHeader('X-Priority', '1')
email.setMsg(str(msg))
email.send()
def _createRequest(self):
return HttpRequest(self.jira_server, self.username, self.password)
def _link(self, issue):
return '[{0}]({1}/browse/{0})'.format(issue, self.jira_server['url'])
This is the calling function. APPid and toAddress will be passed in from different UI.
from Complaince import ComplainceServer
jira = ComplainceServer(jiraServer, username, password)
issues = jira.checkComplaince(appid, toAddress)
I want issueid to be an embedded link.
currently the email sends as below:
MT-4353(https://check.com/login/browse/MT-4353) - Site Sc: DM isg_cq5
but i want [MT-4353] as hyperlink to the URL https://check.com/login/browse/MT-4353
Firstly, you need to encode your email as html. I'm not familiar with the library you are using so I cannot give an example of this.
I have replaced a snippet of your code with html syntax just to illustrate the point that you are meant to use html syntax to have clickable links in an email.
msg = "<p>WARNING: The below tickets are non-compliant in fortify, please fix them or raise exception.</p>"
issue1 = data['issues'][0]['key']
for item in data['issues']:
issue = item['key']
issues[issue] = item['fields']['summary']
data = u"<a href='{0}'>{1}</a>".format(self._link(issue), item['fields']['summary'])
msg += '<br />'+ data
In future, please ask your questions carefully as your title does not question does not indicate what you are actually meaning. You also have spelling mistakes: Compliant
Oh, I missed the point of self._link(issue) not returning the correct link. It returns MT-4353(https://check.com/login/browse/MT-4353) so you are going to need to extract the link part between the brackets. I suggest a regular expression.

Categories

Resources