kerberos authentication in python - 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 ?

Related

ZeroMQ threw ZMQError on socket bind to an ipc:// protocol address (python)

I'm trying to use the IPC protocol with ZeroMQ in Python.
import sys
import time
from random import randint
import zmq
def main(url=None):
ctx = zmq.Context.instance()
publisher = ctx.socket(zmq.PUB)
if url:
publisher.bind(url)
else:
publisher.bind('ipc://var/run/fast-service')
# Ensure subscriber connection has time to complete
time.sleep(1)
# Send out all 1,000 topic messages
for topic_nbr in range(1000):
publisher.send_multipart([
b"%03d" % topic_nbr,
b"Save Roger",
])
if __name__ == '__main__':
main(sys.argv[1] if len(sys.argv) > 1 else None)
It gives the following error:
Traceback (most recent call last):
File "pathopub.py", line 43, in <module>
main(sys.argv[1] if len(sys.argv) > 1 else None)
File "pathopub.py", line 19, in main
publisher.bind("ipc://var/run/fast-service")
File "zmq/backend/cython/socket.pyx", line 547, in zmq.backend.cython.socket.Socket.bind
zmq.error.ZMQError: No such file or directory for ipc path "var/run/fast-service".
I don't understand why would this happen with the socket.bind() function, since in the documentation it says:
When binding a socket to a local address using zmq_bind() with the ipc transport, the endpoint shall be interpreted as an arbitrary string identifying the pathname to create.
which means that it is not necessary to supply an already created directory.
The URL scheme is ipc://. You need to add an absolute path /var/run/fast-service. So,
publisher.bind('ipc:///var/run/fast-service')
More generally the URL is ipc://<host>/<path>. You want local host, so that part is empty. A file system URL is similar, file:///home/foo/bar.txt references /home/foo/bar.txt on the local host.

ImportError: cannot import name CertificateError

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.

Why am I still getting the error: "CryptoUnavailableError: No crypto library available" in Python?

I am trying to make an API call through Python to Google's DFA and am using their suggested code. However, it is still not saying the credentials object is defined and throws the error:
Traceback (most recent call last):
File "<input>", line 2, in <module>
File "C:\Python27\lib\site-packages\oauth2client\util.py", line 137, in positional_wrapper
return wrapped(*args, **kwargs)
File "C:\Python27\lib\site-packages\oauth2client\client.py", line 1502, in __init__
_RequireCryptoOrDie()
File "C:\Python27\lib\site-packages\oauth2client\client.py", line 1456, in _RequireCryptoOrDie
raise CryptoUnavailableError('No crypto library available')
CryptoUnavailableError: No crypto library available
I have installed the pyOpenSSL library, and pycrypto library with the VCForPython compiler. I have also managed to edit all 3 app.yaml files in the LiClipse client to append:
libraries:
- name: pycrypto
version: "latest"
onto it.
This is what my code looks like so far with arbitrary credentials:
import json
import sys
import apiclient
from oauth2client import crypt
import ssl
import urllib2
from OpenSSL import crypto
HAS_OPENSSL = False
HAS_CRYPTO = False
try:
from oauth2client import crypt
HAS_CRYPTO = True
if crypt.OpenSSLVerifier is not None:
HAS_OPENSSL = True
except ImportError:
pass
from oauth2client.client import SignedJwtAssertionCredentials
client_email = 'example.apps.googleusercontent.com'
with open("C:\My Project-1234.p12") as f:
private_key = f.read()
credentials = SignedJwtAssertionCredentials(client_email, private_key,
'https://www.googleapis.com/auth/dfareporting')
from httplib2 import Http
I realize there is probably some excess in the beginning. I have not been able to get past this step.
I feel like I have tried everything and am still getting thrown the 'no crypto library' error.
Can anyone help? THANK YOU!
PS - I am using Windows 7 and Python 2.7 and LiClipse.
The above method was to make an API call as a 'service' Google account. I retried as an 'installed application' account with new credentials and a different way to make the API call which did not require any crypto type libraries.

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

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