ImportError: cannot import name CertificateError - python

The below code throws the following error:
Traceback (most recent call last):
File "./python_PAN_traffic_scraper.py", line 4, in <module>
import urllib3
File "/usr/lib/python2.7/site-packages/urllib3/__init__.py", line 10, in <module>
from .connectionpool import (
File "/usr/lib/python2.7/site-packages/urllib3/connectionpool.py", line 29, in <module>
from ssl import CertificateError
ImportError: cannot import name CertificateError
What am I doing wrong? I want to browse to the firewall portal interface which uses a self-signed certfificate and throws a certificate error when attempting to browse to the site using a specific API URL and API key. Ultimately, I want to expand the code to parse through the XML to look for specific tags and attributes (source / destination / ports / etc).
#!/usr/bin/env python
import ssl
import urllib
import urllib3
import xml.etree.ElementTree as ET
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
DAL = "1.1.1.1"
CHI = "2.2.2.2"
firewall_ip = [ 'Dallas', 'Chicago' ]
datacenter=raw_input('Which firewall do you want traffic logs for? \"DAL\" or \"CHI\"?: ')
contents = ""
cmd = "/api/?type=log&log-type=traffic&query=(receive_time geq '2017/1/22 23:00:00')"
key = "&key=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa="
url = "https://"+pan_ip[0]+urllib3.urlencode(cmd)+key
response = urllib3.urlopen(url, verify=False)
contents = ET.fromstring(response.read())
if DC is "DAL":
print contents
else:
print "Goodbye"
#result = ""
#for i in contents[0][0]:
# if i[0][0].tag == entry:
# for j in i[0][0]:
# if j.tag == 'src' and j.text == src:
# result = i.attrib['name']
#print result

I uninstalled urllib3 and did a fresh install:
$ git clone git://github.com/shazow/urllib3.git
cd to the folder containing urllib3/
$ python setup.py install
This got rid of the error completely.

Related

kerberos authentication in python

we have a database running MSSQL 2008 and I am using below Python (2.7) code to authenticate using Kerberos.
import urllib2
from urlparse import urlparse
from socket import gethostbyaddr
from sspi import ClientAuth
from base64 import b64encode, b64decode
def getService(url):
return 'host/{}'.format(
gethostbyaddr(
urlparse(url).netloc.split(':')[0]
)[0][:-16]
)
status, buff = 1, None
c = ClientAuth('Kerberos', targetspn=getService(url))
while status != 0:
status, buff = c.authorize(buff)
tgt = b64encode(buff[0].Buffer)
authorization_header = \
("Negotiate " + tgt)
When I try this code in python console, getService can resolve the address correctly giving me
host/SQLSERVER1
but when I do status, buff = c.authorize(buff) it gives me
Traceback (most recent call last): File "", line 1, in
File "C:\python27\lib\site-packages\win32\lib\sspi.py",
line 139, in authorize
sec_buffer_out) pywintypes.error: (-2146893053, 'InitializeSecurityContext', 'The specified target is unknown or
unreachable')
Why does it say The specified target is unknown or unreachable? when I can ping it and gethostbyaddr as well ? is there anyway to resolve this ?

Need to turn python 3 script to python 2.7 script

I had this Python 3 script and now I need it to run on Python 2,
from what I have read urilib should change to urlib2.
But it looks like there was a change in the encoding class.
because I get this error:
16:29:27 + python p.py
16:29:27 Traceback (most recent call last):
16:29:27 File "p.py", line 20, in <module>
16:29:27 binary_data = params.encode(encoding=repr,errors=strict)
16:29:27 NameError: name 'strict' is not defined
This is my Python 3 script:
import urllib
import urllib.request
import sys
import os
url = 'http://google.com'
params = urllib.parse.urlencode({
'profile': 'dev' ,
'KEY':'bdi.key' ,
})
binary_data = params.encode(encoding='ascii',errors='strict')
response = urllib.request.urlopen(url, binary_data).read()
This is my Python 2 script:
import urllib
import urllib2
from contextlib import closing
import sys
import os
url = 'http://google.com'
params = urllib.urlencode({
'profile': 'dev' ,
'KEY':'bdi.key' ,
})
binary_data = params.encode(encoding=repr,errors=strict)
response = urllib2.urlopen(url, binary_data).read()
How Can I get it to work?
I have never used Python before and this is a maintenance script that I am trying to keep alive :)
Issue is in string encoding function, namely errors parameter. You should put strict into quotes, since variable strict doesn't exist.
So, it should be like this:
binary_data = params.encode(encoding=repr, errors='strict')

Twitter sign in script cannot import name Api

I am using the following code to sign in to twitter:
import simplejson
import twitter
import oauth
import oauthtwitter
from oauthtwitter import OAuthApi
class OauthRequest():
CONSUMER_KEY = ""
CONSUMER_SECRET = ""
AUTHORIZATION_URL = 'http://twitter.com/oauth/authorize'
REQUEST_TOKEN_URL = 'https://twitter.com/oauth/request_token'
def GetRequest(self):
vOauthApi = OAuthApi(self.CONSUMER_KEY, self.CONSUMER_SECRET)
self.mOauthRequestToken = vOauthApi.getRequestToken(self.REQUEST_TOKEN_URL)
self.mOauthRequestUrl = vOauthApi.getAuthorizationURL(self.mOauthRequestToken)
However, I receive the following error message:
Traceback (most recent call last):
File "C:\Python33\twitter.py", line 4, in <module>
import oauthtwitter
File "C:\Python33\lib\site-packages\oauthtwitter.py", line 17, in <module>
from twitter import Api, User
ImportError: cannot import name Api
I have installed PIP and downloaded the 'oauth', 'oauthtwitter' and 'twitter' modules using it. I am running Windows Vista and Python 3.3. As far as I can tell in my 'Lib' folder the files are there for oauthtwitter.
I'm noy sure exactly what is going wrong here?
Thanks

File Too Large to import?

I just wrote this code to fetch the wireshark mac oui database, and I get the following error:
Traceback (most recent call last):
File "init.py", line 38, in <module>
main()
File "init.py", line 27, in main
import maclist
File "/home/synthetica/WiJam/maclist.py", line 23753
'FC:F6:4
however, this is NOT the contents of the file at that line. Is this a limit of the python intepreter, something I'm overlooking, or something else?
init.py:
def main():
#init
#Load config.
import localconfig
print localconfig.name
#update mac adress db, if at all possible:
try:
import maclist
except:
import urllib2
print "Fetching MAC adress db."
try:
maclist = urllib2.urlopen(localconfig.url)
else:
fl = open("maclist.py","w")
fl.write("#maclist.py generated by "+localconfig.name+"\n")
print "Generating maclist.py"
for line in maclist:
if "#" in line: line=line[:line.index("#")]
line = line.split()
if line and "-" not in line[0]:
line=[repr(part) for part in line]
line = "=".join(line)
fl.write("=".join(line.split())+"\n")
import maclist
#start browser
#start web interface
#handle web interface commands
#display web interface
if __name__=="__main__":
main()
localconfig.py
version = "0.3"
name = "Synth's WiJam (version "+version+")"
#maclist related:
url = "https://code.wireshark.org/review/gitweb?p=wireshark.git;a=blob_plain;f=manuf;hb=HEAD"
Any leads?
#bren
maclist.py: Not the full thing, heavens no. It's 20k+ lines.
'FC:E1:92'='SichuanJ'
'FC:E1:D9'='StableIm'
'FC:E2:3F'='ClayPaky'
'FC:E5:57'='Nokia'
'FC:E8:92'='Hangzhou'
'FC:ED:B9'='Arrayent'
'FC:F1:CD'='Optex-Fa'
'FC:F5:28'='ZyxelCom'
'FC:F6:47'='Fiberhom'
'FC:F8:AE'='IntelCor'
'FC:F8:B7'='TronteqE'
'FC:FA:F7'='Shanghai'
'FC:FB:FB'='Cisco'
Rewrite maclist.py to be proper python syntax, for example:
hosts={}
hosts['FC:FA:F7']='Shanghai'
hosts['FC:FB:FB']='Cisco'
and so on.

No module named v4.proto.omni

I have installed pysnmp-4.x.I am getting following error during running a SNMP program.
I am using pysnmpSE 3.5.2 now but getting same error. I found that pysnmpSE doesn't hav v4 module. I was suggested that following error should resolved if pySNMP SE 3.x is used.
Traceback (most recent call last):
File "C:\Documents and Settings\ggne0622\Desktop\Python\google-python-exercises\babynames\SimpleAgent.py", line 18, in <module>
from twistedsnmp import agent, agentprotocol, bisectoidstore
File "C:\Python27\Lib\site-packages\twistedsnmp\agent.py", line 4, in <module>
from twistedsnmp import datatypes
File "C:\Python27\Lib\site-packages\twistedsnmp\datatypes.py", line 7, in <module>
from twistedsnmp.pysnmpproto import v2c,v1
File "C:\Python27\Lib\site-packages\twistedsnmp\pysnmpproto.py", line 13, in <module>
from pysnmp.v4.proto.omni import v2c,v1, error, rfc1157, rfc1905
ImportError: No module named v4.proto.omni
Code:
#!/usr/bin/env python
from twisted.internet.iocpreactor import reactor
from twisted.internet import error as twisted_error
from twistedsnmp import agent, agentprotocol, bisectoidstore
#from twisted.internet import interfaces
try:
from twistedsnmp import bsdoidstore
except ImportError:
import warnings
warnings.warn( """No BSDDB OID Storage available for testing""" )
bsdoidstore = None
def createAgent( oids ):
ports = [161]+range(20000,25000)
for port in ports:
try:
`agentObject = reactor.IOCPReactor.listenUDP(port,` `agentprotocol.AgentProtocol(snmpVersion = 'v2c',agent = agent.Agent(dataStore =` `bisectoidstore.BisectOIDStore(OIDs = oids,),),),)`
`except twisted_error.CannotListenError:`
`pass`
`else:`
`return agentObject, port`
testingOIDs = {
'.1.3.6.1.2.1.1.1.0': 'Some tool out in the field',
'.1.3.6.1.2.1.1.2.0': '.1.3.6.1.4.1.88.3.1',
'.1.3.6.1.2.1.1.3.0': 558566090,
'.1.3.6.1.2.1.1.4.0': "support#somewhere.ca",
'.1.3.6.1.2.1.1.5.0': "NameOfSystem",
'.1.3.6.1.2.1.1.6.0': "SomeHeadEnd, West Hinterlands, Canada",
}
def main(oids=testingOIDs):
agent, port = createAgent( oids )
if __name__ == "__main__":
reactor.IOCPReactor.callWhenRunning( main )
reactor.IOCPReactor.run()
TwistedSNMP does not seem to be designed to work with PySNMP 4.x. Thus you should either use PySNMP 3.x / PySNMP SE or switch to PySNMP 4.x which has its own Twisted binding.

Categories