Downloading a file with LDAP authentication - python-2.7

I'm trying to find a way to download a CSV from a network URI (not web) that requires LDAP authentication. I have a service account made for this, but I'm not able to find a working solution:
conn = ldap.open("10.41.10.10:389") #I've tried different URIs
conn.simple_bind_s('svc_acct#company.com', 'password')
call = open(r'\\fserv03\reports\gps_List.csv')
Is there a better way to do this?
Updated: Got Python-LDAP to work for my 64 bit install after downloading Python-LDAP to work, I downloaded python_ldap-2.4.28-cp27-cp27m-win_amd64 and running the pip install on it.

I was able to get this to work with the following (using Python-LDAP library):
try:
l = ldap.initialize('ldap://LDAP SERVER HERE')
l.protocol_version = ldap.VERSION2
username = "cn=USER, o=example.com"
password = 'PASSWORD HERE'
l.simple_bind(username, password)
except ldap.LDAPError, e:
print e

Related

Retrieving results from Mturk Sandbox

I'm working on retrieving my HIT results from my local computer. I followed the template of get_results.py and entered my key_id, access_key correctly, and installed xmltodict but got the error message. Could anyone help me figure out why? Here is my HIT address if anyone needs the format of my HIT https://workersandbox.mturk.com/mturk/preview?groupId=3MKP0VNPM2VVY0K5UTNZX9OO9Q8RJE
import boto3
mturk = boto3.client('mturk',
aws_access_key_id = "PASTE_YOUR_IAM_USER_ACCESS_KEY",
aws_secret_access_key = "PASTE_YOUR_IAM_USER_SECRET_KEY",
region_name='us-east-1',
endpoint_url = MTURK_SANDBOX
)
# You will need the following library
# to help parse the XML answers supplied from MTurk
# Install it in your local environment with
# pip install xmltodict
import xmltodict
# Use the hit_id previously created
hit_id = 'PASTE_IN_YOUR_HIT_ID'
# We are only publishing this task to one Worker
# So we will get back an array with one item if it has been completed
worker_results = mturk.list_assignments_for_hit(HITId=hit_id, AssignmentStatuses=['Submitted'])

How can I get around Name too long for LOGINREC in pymssql without changing the username

I am attempting to use pymssql to connect to a client's database, but have thus far been unable to succeed. I believe that the root of the problem is this entry in the stack trace of my TDSDUMP:
dblib.c:761:dbsetlname(0x1ac3e10, <username>#<servername>.database.windows.net, 2)
dblib.c:7929:dbperror((nil), 20042, 0)
dblib.c:7981:20042: "Name too long for LOGINREC field"
One problem is that <servername>.database.windows.net already exceeds the string limit (which seems to be 30 according to this: How to use PHP's dblib PDO driver with long usernames? / SQLSTATE[HY000] Name too long for LOGINREC field (severity 2)).
I have also attempted to exclude the #<servername>.database.windows.net portion in the username entry only to receive the following error:
msgno 40532: "Cannot open server "1433D" requested by the login. The login failed."
According to https://github.com/pymssql/pymssql/issues/330 the #<servername> portion is requested by the server.
So at this point, I attempted to do the following:
user = username + "#{}".format(server)
user = user[:30]
And I received the following information (which was a slight improvement but still not ideal, given that I could still not establish the connection):
"Cannot open server "<server_name minus the last 6 characters>" requested by the login. The login failed."
If possible, I would prefer passing some parameter to pymssql's connect method that would override this character limit or do something to append the server to the username on the backend after calling dbsetlname on just <username> without the #<servername> portion. Does anyone have any recommendations (again the preference is to not ask the client to change our username, but we may have to resort to that or trying to use pyodbc if there's no other option).
These are a few of the connection methods I have tried:
conn = pymssql.connect(
host=host,
database=database,
user=username,
password=password,
port=int(port) # this is 1433
)
conn = pymssql.connect(
host=host,
database=database,
user=username + '#{}'.format(servername),
password=password,
port=int(port) # this is 1433
)
conn = pymssql.connect(
server=<servername>.database.windows.net,
database=database,
user=username,
password=password,
port=int(port) # this is 1433
)
Thanks in advance for any help/advice that you may be able to offer!
You can probably use an alternate connecting string method.
If you're using SQL Server Auth, try this:
conn = pymssql.connect(
server="<servername>.database.windows.net",
port=1433,
user="username",
password="password",
database="dbname"
)
If you're using Windows Auth:
conn = pymssql.connect(
server="<servername>.database.windows.net",
port=1433,
user="DOMAIN\USERNAME",
password="password",
database="dbname"
)
Have you tried either of these connect methods?

Setting Spotify credentials using Spotipy

I am trying out spotipy with python 2.7.10 preinstalled on my mac 10.10, specifically [add_a_saved_track.py][1] Here is the code as copied from github:
# Add tracks to 'Your Collection' of saved tracks
import pprint
import sys
import spotipy
import spotipy.util as util
scope = 'user-library-modify'
if len(sys.argv) > 2:
username = sys.argv[1]
tids = sys.argv[2:]
else:
print("Usage: %s username track-id ..." % (sys.argv[0],))
sys.exit()
token = util.prompt_for_user_token(username, scope)
if token:
sp = spotipy.Spotify(auth=token)
sp.trace = False
results = sp.current_user_saved_tracks_add(tracks=tids)
pprint.pprint(results)
else:
print("Can't get token for", username)
I registered the application with developer.spotify.com/my-applications and received client_id and client_secret. I am a bit unclear about selection of redirect_uri so I set that to 'https://play.spotify.com/collection/songs'
Running this from terminal I get an error that says:
You need to set your Spotify API credentials. You can do this by
setting environment variables like so:
export SPOTIPY_CLIENT_ID='your-spotify-client-id'
export SPOTIPY_CLIENT_SECRET='your-spotify-client-secret'
export SPOTIPY_REDIRECT_URI='your-app-redirect-url'
I put that into my code with the id, secret, and url as strings, just following the imports but above the util.prompt_for_user_token method.
That caused a traceback:
File "add-track.py", line 8
export SPOTIPY_CLIENT_ID='4f...6'
^
SyntaxError: invalid syntax
I noticed that Text Wrangler does not recognize 'export' as a special word. And I searched docs.python.org for 'export' and came up with nothing helpful. What is export? How am I using it incorrectly?
I next tried passing the client_id, client_secret, and redirect_uri as arguments in the util.prompt_for_user_token method like so:
util.prompt_for_user_token(username,scope,client_id='4f...6',client_secret='xxx...123',redirect_uri='https://play.spotify.com/collection/songs')
When I tried that, this is what happens in terminal:
User authentication requires interaction with your
web browser. Once you enter your credentials and
give authorization, you will be redirected to
a url. Paste that url you were directed to to
complete the authorization.
Opening https://accounts.spotify.com/authorize?scope=user-library-modify&redirect_uri=https%3A%2F%2Fplay.spotify.com%2Fcollection%2Fsongs&response_type=code&client_id=4f...6 in your browser
Enter the URL you were redirected to:
I entered https://play.spotify.com/collection/songs and then got this traceback:
Traceback (most recent call last):
File "add-track.py", line 21, in <module>
token = util.prompt_for_user_token(username, scope, client_id='4f...6', client_secret='xxx...123', redirect_uri='https://play.spotify.com/collection/songs')
File "/Library/Python/2.7/site-packages/spotipy/util.py", line 86, in prompt_for_user_token
token_info = sp_oauth.get_access_token(code)
File "/Library/Python/2.7/site-packages/spotipy/oauth2.py", line 210, in get_access_token
raise SpotifyOauthError(response.reason)
spotipy.oauth2.SpotifyOauthError: Bad Request
It seems like I am missing something, perhaps another part of Spotipy needs to be imported, or some other python module. It seems I am missing the piece that sets client credentials. How do I do that? I am fairly new at this (if that wasn't obvious). Please help.
UPDATE: I changed redirect_uri to localhost:8888/callback. That causes a Firefox tab to open with an error -- "unable to connect to server." (Since I do not have a server running. I thought about installing node.js as in the Spotify Web API tutorial, but I have not yet). The python script then asks me to copy and paste the URL I was redirected to. Even though FF could not open a page, I got this to work by copying the entire URL including the "code=BG..." that follows localhost:8888/callback? I am not sure this is an ideal setup, but at least it works.
Does it matter if I set up node.js or not?
The process you've followed (including your update) is exactly as the example intends and you are not missing anything! Obviously, it is a fairly simple tutorial, but it sets you up with a token and you should be able to get the information you need.
For the credentials, you can set these directly in your Terminal by running each of the export commands. Read more about EXPORT here: https://www.cyberciti.biz/faq/linux-unix-shell-export-command/

Encoding is not kept

I am using Python 2.7 and using google plus public API to get activity data in a file. I am encountering issues to maintain the json encoding in my file. Double quotes are coming as u'' in my file. Below is my code:
from apiclient import discovery
API_KEY = 'MY API KEY'
service = discovery.build("plus", "v1", developerKey=API_KEY)
activities_resource = service.activities()
request = activities_resource.search(query='India versus South Africa', maxResults=1, orderBy='best',)
while request!= None:
activities_document = request.execute()
if 'items' in activities_document:
with open("output.json", mode='a') as file:
data = str(activities_document['items'])
file.write(data +"\n\n")
request = service.activities().list_next(request, activities_document)
Output:
[{u'kind': u'plus#activity', u'provider': {u'title': u'Google+'}, u'titl.......
I am expecting [{"kind": "plus#activity", .....
I am running my code on windows and I have tried both on DOS and pycharm IDE. I have also run the code on ubuntu machine but same output. Please let me know what I am doing wrong.
The json module is used for generating JSON. Use it.

unable to get remote addr request.META ['REMOTE_ADDR'] not working

hi
i am unable to get ip address of the user connecting to my site under django 1.1.1.
ip_address=request.META['REMOTE_ADDR']
em using python 2.6 django 1.1.1 under ubuntu 10.10
i have also installed the middle ware and tried this method also
'django.middleware.http.SetRemoteAddrFromForwardedFor'
try:
ip_address=request.META['HTTP_X_FORWARDED_FOR']
except KeyError:
pass
else:
# HTTP_X_FORWARDED_FOR can be a comma-separated list of IPs.
# Take just the first one.
ip_address = ip_address.split(",")[0]
request.META['REMOTE_ADDR'] = ip_address
and in the templates i also tried to get IP using {{ request.REMOTE_ADDR }}
but unable to get the IP
what will be the reason for this
any help wil be greatly appreaciated thanks
the problem is solved
i dont know what was the issue but re installation
of django solved solved the problem