Handling Authentication Retrieving a Image from authenicated website Via urllib2 - image

I am trying to make a small API that logs into a internal monitoring tool via web and retrieves images on pages that I specify using the login credentials I specify. It's not passing any authentication to the last section after it has already built the URL. After the URL is built, it is put into variable y. I then attempt to open y and save it, that is where the authentication problem is happening. Please scroll down for examples.
import urllib
import urllib2
import lxml, lxml.html
ID = raw_input("Enter ID:")
PorS = raw_input("Enter 1 for Primary 2 for Secondary:")
base_link = 'http://statseeker/cgi/nim-report?rid=42237&command=Graph&mode=ping&list=jc-'
dash = '-'
end_link = '&tfc_fav=range+%3D+start_of_today+-+1d+to+now%3B&year=&month=&day=&hour=&minute=&duration=&wday_from=&wday_to=&time_from=&time_to=&tz=America%2FChicago&tfc=range+%3D+start_of_today+-+1d+to+now%3B&rtype=Delay&graph_type=Filled&db_type=Average&x_step=1&interval=60&y_height=100&y_gridlines=5&y_max=&y_max_power=1&x_gridlines=on&legend=on'
urlauth = base_link + jConnectID + dash + jConnectPorS + end_link
print urlauth
realm = 'statseeker'
username = 'admin'
password = '*****'
auth_handler = urllib2.HTTPBasicAuthHandler()
auth_handler.add_password(realm, urlauth, username, password)
opener = urllib2.build_opener(auth_handler)
urllib2.install_opener(opener)
data = opener.open(urlauth).read()
html = lxml.html.fromstring(data)
imgs = html.cssselect('img.graph')
for x in imgs:
y = 'http://statseeker%s' % (x.attrib['src'])
g = urllib2.urlopen(y).read()
urllib2.urlopen(test.jpg, 'wb').write(g)
print 'http://statseeker%s' % (x.attrib['src'])
with open('statseeker.html', 'a') as f:
f.write(y)
Result:
C:\Users\user\Documents\Scripting>python test.py
Enter ID:4050
Enter 1 for Primary 2 for Secondary:1
http://statseeker/cgi/nim-report?rid=42237&command=Graph&mode=ping&list=jc-4050-
1&tfc_fav=range+%3D+start_of_today+-+1d+to+now%3B&year=&month=&day=&hour=&minute
=&duration=&wday_from=&wday_to=&time_from=&time_to=&tz=America%2FChicago&tfc=ran
ge+%3D+start_of_today+-+1d+to+now%3B&rtype=Delay&graph_type=Filled&db_type=Avera
ge&x_step=1&interval=60&y_height=100&y_gridlines=5&y_max=&y_max_power=1&x_gridli
nes=on&legend=on
Traceback (most recent call last):
File "JacksonShowAndSave.py", line 35, in <module>
g = urllib2.urlopen(y).read()
File "C:\Python27\lib\urllib2.py", line 127, in urlopen
return _opener.open(url, data, timeout)
File "C:\Python27\lib\urllib2.py", line 410, in open
response = meth(req, response)
File "C:\Python27\lib\urllib2.py", line 523, in http_response
'http', request, response, code, msg, hdrs)
File "C:\Python27\lib\urllib2.py", line 448, in error
return self._call_chain(*args)
File "C:\Python27\lib\urllib2.py", line 382, in _call_chain
result = func(*args)
File "C:\Python27\lib\urllib2.py", line 531, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 401: Authorization Required
C:\Users\user\Documents\Scripting>
How do I fix these errors to pass the Authentication to any web page opened on that website? I thought that any urlopen request would use the same authentication as above.
The Section that is Failing:
y = 'http://statseeker%s' % (x.attrib['src'])
g = urllib2.urlopen(y).read()
urllib2.urlopen(test.jpg, 'wb').write(g)
print 'http://statseeker%s' % (x.attrib['src'])
with open('statseeker.html', 'a') as f:

I built another auth handler for the request:
auth_handler2 = urllib2.HTTPBasicAuthHandler()
auth_handler2.add_password(realm, y, username, password)
opener2 = urllib2.build_opener(auth_handler2)
urllib2.install_opener(opener2)
link = urllib2.Request(y)
response = urllib2.urlopen(link)
output = open('out2.jpg','wb')
output.write(response.read())
output.close()

Related

TypeError: _Captcha.write() missing 1 required positional argument: 'output'

I'm trying to create a captchat command but I can't. What I'd like is that when we do /verify it sends us a photo composed of 7 numbers in a private message and if we copy the 7 numbers on the photo to the identiquet it gives us the verify role and when we have the role we can't execute the command.
async def verify(ctx):
sender = ctx.author
image = ImageCaptcha(width = 280, height = 90)
captcha_text = random.randint(1000000, 9999999)
captcha_text = str(captcha_text)
data = image.generate(captcha_text)
await ctx.send('look at your PM')
image.write(captcha_text)
await sender.send('ok its what the captcha', file=discord.File('captcha/CAPTCHA.png'))
print(captcha_text)
while True:
msg = await bot.wait_for("message", check=lambda check: check.author.id == ctx.author.id)
if msg.guild == None:
break
print(msg.content)
if msg.content == captcha_text:
await sender.send('Correct you have been checked!')
role=discord.utils.get(ctx.guild.roles, name='Check')
await sender.add_roles(role)
else:
await sender.send('Incorrect try again!')
and here are the errors that I obtain
File "f:\tout les dossier\discord tools\les logiciel\les mien\RAID\Anti Raid.py", line 188, in verify
image.write(captcha_text)
TypeError: _Captcha.write() missing 1 required positional argument: 'output'
would you have the solution?
Read the error. It's telling you that you need to specify where to output the image
In your case, replace the line
image.write(captcha_text)
with
image.write(captcha_text, 'captcha/CAPTCHA.png')

My discord bot's command code on Python won't execute for some reason

This is a code of mine that make my bot get access to Reddit post by using user's argument:
#bot.command()
async def reddit(ctx, *, args):
global block, embed
keywords = ""
sub = ['memes', 'showerthoughts', 'jokes', 'antijokes']
if args:
for i in range(0, len(sub)):
if sub[i] in args:
keywords = sub[i]
break
else:
await ctx.send("The sub-reddit is invalid, dear dummy.")
return
block = await ctx.send(f"Fetching {keywords}...")
for count in range(1, 5):
await asyncio.sleep(0.05)
await block.edit(content=f"Fetching {keywords}...`{str(count)}/5`")
count += 1
subreddit = reddit.subreddit(keywords)
all_subs = []
top = subreddit.top(limit=50)
for submission in top:
all_subs.append(submission)
random_sub = random.choice(all_subs)
name = random_sub.title
url = random_sub.url
text = random_sub.selftext
embed = discord.Embed(title=name, color=discord.Color.green(), description=text)
embed.set_image(url = url)
embed.set_footer(text=f"Asked by {ctx.message.author.display_name}")
await block.edit(embed=embed)
The problem is it seem to cause error:
Ignoring exception in on_command_error
Traceback (most recent call last):
File "C:\Users\admin\PycharmProjects\pythonProject\venv\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "C:/Users/admin/PycharmProjects/pythonProject/main.py", line 23, in on_command_error
timeleft = round(error.retry_after, 2);
AttributeError: 'CommandInvokeError' object has no attribute 'retry_after'
This is the code it refered to:
#bot.event
async def on_command_error(ctx, error):
timeleft = round(error.retry_after, 2);
if isinstance(error, commands.CommandOnCooldown):
await ctx.send(f'Wah, spicy. Stop spamming. Try it again after `{timeleft}` seconds')
The code works just fine, however, only when I try to execute the reddit command, it begin to throw the above errors. I have no idea why this happenned.
Turn out it's because of the duplicate name of existed reddit variable. Beginner mistake, as expected from a total beginner like me. The problem is solved.

Google Classroom API Python list Coursework

I am trying to get all assignments from a users classes and for some reason, it gives me this error:
Traceback (most recent call last):
File "C:/Users/oscar/Desktop/Development/Python/main.py", line 50, in <module>
main()
File "C:/Users/oscar/Desktop/Development/Python/main.py", line 29, in main
creds = flow.run_local_server(port=0)
File "C:\Users\oscar\Desktop\Development\Python\venv\lib\site-packages\google_auth_oauthlib\flow.py", line 474, in run_local_server
self.fetch_token(authorization_response=authorization_response)
File "C:\Users\oscar\Desktop\Development\Python\venv\lib\site-packages\google_auth_oauthlib\flow.py", line 288, in fetch_token
return self.oauth2session.fetch_token(self.client_config["token_uri"], **kwargs)
File "C:\Users\oscar\Desktop\Development\Python\venv\lib\site-packages\requests_oauthlib\oauth2_session.py", line 360, in fetch_token
self._client.parse_request_body_response(r.text, scope=self.scope)
File "C:\Users\oscar\Desktop\Development\Python\venv\lib\site-packages\oauthlib\oauth2\rfc6749\clients\base.py", line 421, in parse_request_body_response
self.token = parse_token_response(body, scope=scope)
File "C:\Users\oscar\Desktop\Development\Python\venv\lib\site-packages\oauthlib\oauth2\rfc6749\parameters.py", line 431, in parse_token_response
validate_token_parameters(params)
File "C:\Users\oscar\Desktop\Development\Python\venv\lib\site-packages\oauthlib\oauth2\rfc6749\parameters.py", line 461, in validate_token_parameters
raise w
Warning: Scope has changed from "https://www.googleapis.com/auth/classroom.courses.readonly https://www.googleapis.com/auth/classroom.coursework.me.readonly" to "https://www.googleapis.com/auth/classroom.student-submissions.me.readonly https://www.googleapis.com/auth/classroom.courses.readonly".
Process finished with exit code 1
Here is my code:
from __future__ import print_function
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
# If modifying these scopes, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/classroom.courses.readonly', 'https://www.googleapis.com/auth/classroom.coursework.me.readonly']
def main():
"""Shows basic usage of the Classroom API.
Prints the names of the first 10 courses the user has access to.
"""
creds = None
# The file token.json stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.json'):
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.json', 'w') as token:
token.write(creds.to_json())
service = build('classroom', 'v1', credentials=creds)
# Call the Classroom API
results = service.courses().list(pageSize=10).execute()
courses = results.get('courses', [])
if not courses:
print('No courses found.')
else:
for course in courses:
print(course['name'])
course_id = course['id']
results1 = service.courses().courseWork().list(courseId=course_id).execute()
print(results1)
if __name__ == '__main__':
main()
I think this is happening because of the second scope but it's the one they say to use on the official API so Idk why its giving me an error. Any help would be appreciated.

Raspberrypi Python code not working proprely

I want use this code to get cpu temperature from my raspberry_pi and if the temperature is too high sending an warn email , the code show below:
# coding=utf-8
import os
import smtplib
from email.mime.text import MIMEText
# At First we have to get the current CPU-Temperature with this defined function
def getCPUtemperature():
res = os.popen('vcgencmd measure_temp').readline()
return (res.replace("temp=", "").replace("'C\n", ""))
# Now we convert our value into a float number
temp = float(getCPUtemperature())
# Check if the temperature is abouve 30°C (test with 30)
if (temp > 30):
# Enter your smtp Server-Connection
server = smtplib.SMTP('smtpmail.provider.com', 587)
# if your using gmail: smtp.gmail.com
server.ehlo()
server.starttls()
server.ehlo
# Login
server.login("your email or username", "your Password")
# Now comes the Text we want to send:
value = "Critical warning! The actual temperature is: " + getCPUtemperature()
msg = MIMEText(value)
# The Subject of your E-Mail
msg['Subject'] = "Critical warning! Temperature:" + getCPUtemperature()
# Consigner of your E-Mail
msg['From'] = "Raspberry Pi"
# recipient of your E-Mail
msg['To'] = "recipient#gmail.com"
# Finally send the mail
server.sendmail("consigner#gmail.com", "recipient#gmail.com", msg.as_string())
server.quit()
print "Everything was working fine! Best regards www.quaintproject.wordpress.com"
this code should working and had previous successful examples , but when I run it the output like this:
pi#raspberrypi:~ $ sudo nano tempwarn.py
pi#raspberrypi:~ $ sudo python tempwarn.py
Traceback (most recent call last):
File "tempwarn.py", line 20, in <module>
server = smtplib.SMTP('smtpmail.provider.com', 587)
File "/usr/lib/python2.7/smtplib.py", line 256, in __init__
(code, msg) = self.connect(host, port)
File "/usr/lib/python2.7/smtplib.py", line 317, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "/usr/lib/python2.7/smtplib.py", line 292, in _get_socket
return socket.create_connection((host, port), timeout)
File "/usr/lib/python2.7/socket.py", line 557, in create_connection
for res in getaddrinfo(host, port, 0, SOCK_STREAM):
socket.gaierror: [Errno -2] Name or service not known
why it has this kind of error? and im pretty sure the 587 is correct setting for gmail.
swap smtpmail.provider.com to smtp.gmail.com

How do I test my AJAX function defined in my views file?

I'm using Django and Python 3.7 and tryihng to tests an AJAX request from a view, located at web/views/tax_calculator.py
# Basic function that serves the default page
def get(request):
return render(request, "web/template/tax_calculator.html", {})
# This is an Ajax call that will calculate the overall taxes you pay for
# an S-Corp vs a sole proprietorship
def post(request):
state = request.GET.get('state', None)
gross_income = request.GET.get('gross', None)
owner_salary = request.GET.get('salary', None)
data = {
'sole_pr_taxes': TaxCalculatorService.calc_sole_pr_taxes(state, gross_income),
's_corp_taxes': TaxCalculatorService.calc_s_corp_taxes(state, gross_income, owner_salary),
}
return JsonResponse(data)
Here is my test file, located at web/tests/test_views.py
from django.test.client import Client
import json
from web.models import *
c = Client()
class ViewTests(TestCase):
# Basic test to verify we can get valid return data
def test_calculate_tax(self):
state = 'MN'
gross = 100000
salary = 75000
json_data = json.dumps({'state': state,
'gross': gross,
'salary': salary})
response = c.post('/content/vote/', json_data,
content_type='application/json',
HTTP_X_REQUESTED_WITH='XMLHttpRequest')
self.assertEqual(response.status_code, 302) # this is OK.
print(response.content)
self.assertEqual(response.content, 2)
This results in the error below. What else do I need to do to make my test understand my Ajax request?
======================================================================
ERROR: test_calculate_tax (web.tests.test_views.ViewTests)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/davea/Documents/workspace/myproject/web/tests/test_views.py", line 20, in test_calculate_tax
response = c.post('/content/vote/', json_data,
AttributeError: 'Client' object has no attribute 'post'
----------------------------------------------------------------------
Ran 2 tests in 0.010s

Resources