Diagnosing proxy issue with python - python-2.7

So I am trying to work with python 2.7 to do various things that require pulling data from the internet. I have not been very successful, and I am looking for help to diagnose what I am doing wrong.
Firstly I managed to get pip to work by by defining the proxy like so, pip install --proxy=http://username:password#someproxy.com:8080 numpy. Hence python must be capable of getting through it!
However when it came to actually writing a .py script that could do the same I have had no success. I tried using the following code with urllib2 first:
import urllib2
uri = "http://www.python.org"
http_proxy_server = "someproxyserver.com"
http_proxy_port = "8080"
http_proxy_realm = http_proxy_server
http_proxy_user = "username"
http_proxy_passwd = "password"
# Next line = "http://username:password#someproxyserver.com:8080"
http_proxy_full_auth_string = "http://%s:%s#%s:%s" % (http_proxy_user,
http_proxy_passwd,
http_proxy_server,
http_proxy_port)
def open_url_no_proxy():
urllib2.urlopen(uri)
print "Apparent success without proxy server!"
def open_url_installed_opener():
proxy_handler = urllib2.ProxyHandler({"http": http_proxy_full_auth_string})
opener = urllib2.build_opener(proxy_handler)
urllib2.install_opener(opener)
urllib2.urlopen(uri)
print "Apparent success through proxy server!"
if __name__ == "__main__":
open_url_no_proxy()
open_url_installed_opener()
However I just get this error:
URLError: <urlopen error [Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond>
Then I tried urllib3 as this is the module used by pip to handle proxies:
from urllib3 import ProxyManager, make_headers
# Establish the Authentication Settings
default_headers = make_headers(basic_auth='username:password')
http = ProxyManager("https://www.proxy.com:8080/", headers=default_headers)
# Now you can use `http` as you would a normal PoolManager
r = http.request('GET', 'https://www.python.org/')
# Check data is from destination
print(r.data)
I got this error:
raise MaxRetryError(_pool, url, error or ResponseError(cause)) MaxRetryError: HTTPSConnectionPool(host='www.python.org', port=443): Max retries exceeded with url: / (Caused by ProxyError('Cannot connect to proxy.', error('Tunnel connection failed: 407 Proxy Authorization Required',)))
I would really appreciate any help diagnosing this issue.

The solution to my problem was to use the requests module, see the below thread:
Proxies with Python 'Requests' module
mtt2p list this code which worked for me.
import requests
import time
class BaseCheck():
def __init__(self, url):
self.http_proxy = "http://user:pw#proxy:8080"
self.https_proxy = "http://user:pw#proxy:8080"
self.ftp_proxy = "http://user:pw#proxy:8080"
self.proxyDict = {
"http" : self.http_proxy,
"https" : self.https_proxy,
"ftp" : self.ftp_proxy
}
self.url = url
def makearr(tsteps):
global stemps
global steps
stemps = {}
for step in tsteps:
stemps[step] = { 'start': 0, 'end': 0 }
steps = tsteps
makearr(['init','check'])
def starttime(typ = ""):
for stemp in stemps:
if typ == "":
stemps[stemp]['start'] = time.time()
else:
stemps[stemp][typ] = time.time()
starttime()
def __str__(self):
return str(self.url)
def getrequests(self):
g=requests.get(self.url,proxies=self.proxyDict)
print g.status_code
print g.content
print self.url
stemps['init']['end'] = time.time()
#print stemps['init']['end'] - stemps['init']['start']
x= stemps['init']['end'] - stemps['init']['start']
print x
test=BaseCheck(url='http://google.com')
test.getrequests()

Related

QPython requests SSL error- no available ciphers

Ive been trying to use requests.get for sometime now but I keep getting this error on Qpython
HTTPSConnectionPool(host='google.com', port=443):
Max retries exceeded with url:
/ (Caused by SSLError(
SSLError("bad handshake: Error([('SSL routines',
'ssl_cipher_list_to_bytes', 'no ciphers available')],)",),))
This is my code
import ssl
import requests
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.poolmanager import
PoolManager
from requests.packages.urllib3.util import ssl_
CIPHERS = ( 'ECDHE-RSA-AES256-GCM-SHA384:ECDHE-
ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AElS256-
SHA384: ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-
AES128-GCM-SHA256:ECDHE-RSA-AES128-
SHA256:AES256-SHA' )
class TlsAdapter(HTTPAdapter):
def __init__(self, ssl_options=0, **kwargs):
self.ssl_options = ssl_options
super(TlsAdapter, self).__init__(**kwargs)
def init_poolmanager(self, *pool_args, **pool_kwargs):
ctx = ssl_.create_urllib3_context(ciphers=CIPHERS,
cert_reqs=ssl.CERT_REQUIRED,
options=self.ssl_options)
self.poolmanager = PoolManager(*pool_args,
ssl_context=ctx, **pool_kwargs)
s = requests.session()
adapter = TlsAdapter()
s.mount("https://", adapter)
try:
r = s.get('https://google.com')
print(r)
except Exception as e:
print(e)
Does anyone know what's going wrong here? I thought this would work splendidly. Is this a problem specific to qpython or not too. Because that would explain a lot.
Copied from this issue
import requests
requests.packages.urllib3.util.ssl_.DEFAULT_CIPHERS = "TLS13-CHACHA20-POLY1305-SHA256:TLS13-AES-128-GCM-SHA256:TLS13-AES-256-GCM-SHA384:ECDHE:!COMPLEMENTOFDEFAULT"
after that you can
r=requests.get("https://google.com")
print(r.status_code)

PYMQI return data type issue

I am trying the get IBM MQ Messages out of Queue Manager by reading the queue "SYSTEM.ADMIN.COMMAND.EVENT".
I am getting the following response when I print the message.
How do I convert the following message into a user friendly format after reading the queue:
b'\x00\x00\x00\x07\x00\x00\x00$\x00\x00\x00\x03\x00\x00\x00c\x00\x00\x00\x01\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\tm\x00\x00\x00\x02\x00\x00\x00\x14\x00\x00\x00\x10\x00\x00\x1fA\x00\x00\x00\t\x00\x00\x00\x04\x00\x00\x00
\x00\x00\x0b\xe5\x00\x00\x033\x00\x00\x00\x0cnb153796
\x00\x00\x00\x03\x00\x00\x00\x10\x00\x00\x03\xf3\x00\x00\x00\x03\x00\x00\x00\x04\x00\x00\x00D\x00\x00\x0b\xe7\x00\x00\x033\x00\x00\x000ZANC000.YODA
\x00\x00\x00\t\x00\x00\x000\x00\x00\x1bY\x00\x00\x00
\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00\x00\x004\x00\x00\x0b\xe9\x00\x00\x033\x00\x00\x00
\x00\x00\x00\x03\x00\x00\x00\x10\x00\x00\x03\xf2\x00\x00\x00\x1c\x00\x00\x00\x04\x00\x00\x000\x00\x00\x0b\xea\x00\x00\x033\x00\x00\x00\x1cMQ
Explorer 9.0.0
\x00\x00\x00\x04\x00\x00\x00\x18\x00\x00\x0b\xeb\x00\x00\x033\x00\x00\x00\x04
\x00\x00\x00\x03\x00\x00\x00\x10\x00\x00\x03\xfd\x00\x00\x00\xa1\x00\x00\x00\x14\x00\x00\x00\x10\x00\x00\x1fB\x00\x00\x00\x01\x00\x00\x00\x05\x00\x00\x00\x14\x00\x00\x04\xcd\x00\x00\x00\x01\x00\x00\x03\xf1'
My code is as follows, I am using Python 3.6 and Django 2.1 everything is working fine except the format or the returned message:
Please assist in figuring out how to convert the returned message from PYMQI Queue Get into a user readable format:
#
from django.shortcuts import render
from django.http import HttpResponse
import pymqi
#
queue_manager = "QueueManager"
channel = "Channel"
host = "hostname"
port = "port"
queue_name = "SYSTEM.ADMIN.COMMAND.EVENT"
user = "username"
password = "password"
connection_info = "%s(%s)" % (host, port)
#
#(option, args) = OptionParser
# Create your views here.
def index(request):
#
qmgr = pymqi.connect(queue_manager, channel, connection_info, user, password)
#
queue = pymqi.Queue(qmgr, queue_name)
print(queue.get())
messages = queue.get()
#for message in messages:
# print(type(message))
queue.close()
qmgr.disconnect()
return HttpResponse("MQ Hello Tests %s" % messages.hex())

setting proxy in selenium in python for Firefox Geckodriver

My question is about setting proxy in selenium (3.4.3.) coding in python (2.7) for Firefox (Geckodriver v0.18.0-win64).
The spec at
http://www.seleniumhq.org/docs/04_webdriver_advanced.jsp
provides only a java example.
from selenium import webdriver
PROXY = "94.56.171.137:8080"
class Proxy(object):
def __call__(self):
self.base_url = "https://whatismyip.com"
print self.base_url
# proxy json object
desired_capability = webdriver.DesiredCapabilities.FIREFOX['proxy']={
"httpProxy":PROXY,
"ftpProxy":PROXY,
"sslProxy":PROXY,
#"noProxy":None,
"proxyType":"manual"
}
firefox_profile = webdriver.FirefoxProfile()
firefox_profile.set_preference("browser.privatebrowsing.autostart", True)
self.driver = webdriver.Firefox(executable_path='D:\Code\Drivers\geckodriver',firefox_profile=firefox_profile, capabilities=desired_capability)
self.driver.get(self.base_url)
if __name__ == "__main__":
proxy_test = Proxy()
proxy_test()
I am getting the following Error Message:
selenium.common.exceptions.WebDriverException: Message: Can't load the
profile. Possible firefox version mismatch. You must use GeckoDriver
instead for Firefox 48+.
If I comment the code regarding the proxy, I am able to get the page, in private mode as the profile specified. I think it is the proxy that is messing things up.
Yaso's answer didn't work for me, instead i used this
proxyString = "Ip:port"
desired_capability = webdriver.DesiredCapabilities.FIREFOX
desired_capability['proxy'] = {
"proxyType": "manual",
"httpProxy": proxyString,
"ftpProxy": proxyString,
"sslProxy": proxyString
}
I spent hours finding an answer and I want to share it.
The simple problem was in the proxy specification.
Initially the proxy and port were one string
PROXY = "94.56.171.137:8080"
the answer should make the port as a number
PROXY = "94.56.171.137"
PORT = 8080
Here is the rest of the code
from selenium import webdriver
PROXY = "94.56.171.137"
PORT = 8080
class Proxy(object):
def __call__(self):
self.base_url = "https://whatismyip.com"
print self.base_url
# https://github.com/mozilla/geckodriver
# proxy json object
desired_capability = webdriver.DesiredCapabilities.FIREFOX
desired_capability['proxy']={
"proxyType":"manual",
"httpProxy":PROXY,
"httpProxyPort": PORT,
"ftpProxy":PROXY,
"ftpProxyPort": PORT,
"sslProxy":PROXY,
"sslProxyPort" : PORT
}
firefox_profile = webdriver.FirefoxProfile()
firefox_profile.set_preference("browser.privatebrowsing.autostart", True)
self.driver = webdriver.Firefox(executable_path='D:\Drivers\geckodriver',firefox_profile=firefox_profile, capabilities=desired_capability)
self.driver.get(self.base_url)
if __name__ == "__main__":
proxy_test = Proxy()
proxy_test() code here

Python error "Connection reset by peer" in requests module

My goal is to create a persistent cookie on-the-fly by supplying user id & password and use that cookie in POST request using a session object. But below code returns below exception.
('Connection aborted.', error(54, 'Connection reset by peer'))
class CreatePersistentCookie(): """This class is created to generate a persistent cookie that can further be used through out session for all the service requests being executed"""
class CreatePersistentCookie():
"""This class is created to generate a persistent cookie that can further be
used through out session for all the service requests being executed"""
def __init__(self, headers, data, url, params, authserver):
self.headers = headers
self.data = data
self.url = url
self.params = params
self.authserver = authserver
def generateCookie(self):
with requests.session() as s:
reqsessionObj = s.post(self.authserver,params = self.params)
reqCookie = reqsessionObj.request.headers['Cookie'] # this returns the Cookie i need
regexObj = re.compile(r'act-uat=\S+') # this is my app specific pattern search that returns the exact cookie text i need.
matchObj = regexObj.search(reqCookie)
sessionCookie = matchObj.group()
self.headers['Cookie'] = sessionCookie # adding Cookie attribute in headers.
try:
r = s.post(self.url, data=json.dumps(self.data), headers=self.headers)
return r.raise_for_status()
except requests.exceptions.RequestException as err:
print err
def main():
# Defining the params variable. This contains authentication details such as user id,password & App id.
params = {"accountId": "John",
"accountPassword": "password",
"appIdKey": "5c9773e36fd6ea7cc2f9f8ffd9da3e3"
}
# Defining the authserver variable that contains the host details where authentication happens.
authserver = 'https://auth-uat.com/authenticate'
# creating a object cookieObj from class CreatePersistentCookie that returns persistent cookie.
#print cookies
headers = {'Content-Type': 'application/json;charset=UTF-8',
'Host':'service-uat1.com'}
data = {"appName":"abc","appKey":"abc","type":"jdbc","queryName":"xyz","version":"v1.2","useCache":"false","bindVars":[{"bindVarName":"In_dt","bindVarVal":"2014-05-13"},{"bindVarName":"In_Location","bindVarVal":"USA"}]}
url = 'https://uat1.com/gsf/abc/derf/abc/services/xyz'
cookieObj = CreatePersistentCookie(headers, data, url, params, authserver)
cookieObj.generateCookie()
if __name__ == '__main__':
main()
Connection reset by peer indicates that the server you're trying to connect to is refusing the connection. Normally, there is a handshake between your computer and the website's server, but here for some reason, the server is refusing the connection. I would use the urllib, requests, mechanize, and cookielib modules (some of which only work in Python 2.7). Then, using urllib you can attach a user-client header like Firefox, which will trick the browser into accepting the connection because they will think you are a regular person surfing the web, not a robot.
Try the below command in terminal it worked for me
pip install requests[security]
In my case it worked from Postman but not from python script. Restarting the system fixed it.

Python restkit module connection returns error

I'm attempting to use a script I found online, (https://confluence.atlassian.com/display/DOCSPRINT/The+Simplest+Possible+JIRA+REST+Examples) probably 5+ years old, to access Jira REST API. I have all the modules installed in Pyhton 2.7. However, when run the script I get an error that SimplePool cannot be imported. Having done my Goodiligence (Google searching), I see that SimplePool is deprecated in restkit 4.2.2 (which is the version I have installed). So, the doc that I found (http://pydoc.net/Python/restkit/2.3.0/restkit.pool.simple/) says to use TConnectionManager (which I did with no success). I still get a similar error. So, I stumbled upon another doc (http://benoitc.github.io/restkit/pool.html) and it says to use ConnectionPool, and I still get a similar error. I appreciate any direction given. Here is my code:
import simplejson as json
from restkit import * #added this line after finding the last document
from restkit import Resource, BasicAuth, request
from socketpool import ConnectionPool
SimplePool = ConnectionPool
def rest_test(server_base_url, user, password, issue_key):
'''
Use restkit to make a REST request to JIRA
'''
verbose = False
# A pool of connections
pool = SimplePool(factory=Connection)
# This sends the user and password with the request.
auth = BasicAuth(user, password)
resource_name = "issue"
complete_url = "%s/rest/api/latest/%s/%s" % (server_base_url, resource_name, issue_key)
resource = Resource(complete_url, pool_instance=pool, filters=[auth])
try:
response = resource.get(headers = {'Content-Type' : 'application/json'})
except Exception,ex:
# ex.msg is a string that looks like a dictionary
print "EXCEPTION: %s " % ex.msg
return
# Most successful responses have an HTTP 200 status
if response.status_int != 200:
print "ERROR: status %s" % response.status_int
return
# Convert the text in the reply into a Python dictionary
issue = json.loads(response.body_string())
# Pretty-print the JSON
if verbose:
print json.dumps(issue, sort_keys=True, indent=4)
# The properties of the issue include:
# self, html, key, transitions, expand, fields
print "Issue key: %s" % issue['key']
fields = issue['fields']
for field_name in fields:
field_object = fields[field_name]
print "Field %s = %s" % (field_name, field_object['type'])
# The type of the value of a field depends on the type of the field
if field_name in ["summary"]:
print " Value = %s" % field_object['value']
if __name__ == '__main__':
user = 'myuname'
password = '*****'
server_url = 'http://jira.mysite.com/'
issue_key = 'JRA-219'
rest_test(server_url, user, password, issue_key)
Here is the error returned:
File "simplest_client.py", line 30, in rest_test
pool = SimplePool()
TypeError: __init__() takes at least 2 arguments (1 given)
EXCEPTION: <?xml version="1.0" encoding="UTF-8" standalone="yes"?><status><status-code>404</status-code><message>null for uri: http://jira.mysite.com//rest/api/latest/issue/JRA-219</message></status>