python ldap "Bad search filter" error - ldap

This filter works just fine in my LDAP browser by python ldap won't pick it up:
(&(!objectClass=computer)(sn=*%s*))
resulting in:
Request Method: GET Request
URL: http://localhost:8000/ldap_find/%D0%B1%D0%BE%D0%BB%D0%BE%D1%82/
Django Version: 1.4
Exception Type: FILTER_ERROR
Exception Value: {'desc': 'Bad search filter'}
here's the code that does it:
try:
LDAPClient.connect()
base = AUTH_LDAP_SEARCH_BASE
scope = ldap.SCOPE_SUBTREE
filter = '(&(!objectClass=computer)(sn=*%s*))' % search_string
result_set = list()
result = LDAPClient.client.search(base.encode(encoding='utf-8'), scope, filter.encode(encoding='utf-8'),['cn','mail'])
res_type, res_data = LDAPClient.client.result(result)
for data in res_data:
if data[0]:
result_set.append(data)
return json.dumps(result_set)
except Exception, e:
raise e
finally:
LDAPClient.unconnect()
it works fine with simple filters, like
filter = 'sn=*%s*' % search_string
so I'm guessing this is some kind of escaping of & or something inside ldap lib but can't find the root yet.

The search filter syntax is incorrect. Use (&(sn=*%s*)(!(objectClass=computer))). Search filters are well-documented in RFC4511 and RFC4515.

Related

how to read the console output in python without executing any command

I have an API which gets the success or error message on console.I am new to python and trying to read the response. Google throws so many examples to use subprocess but I dont want to run,call any command or sub process. I just want to read the output after below API call.
This is the response in console when success
17:50:52 | Logged in!!
This is the github link for the sdk and documentation
https://github.com/5paisa/py5paisa
This is the code
from py5paisa import FivePaisaClient
email = "myemailid#gmail.com"
pw = "mypassword"
dob = "mydateofbirth"
cred={
"APP_NAME":"app-name",
"APP_SOURCE":"app-src",
"USER_ID":"user-id",
"PASSWORD":"pw",
"USER_KEY":"user-key",
"ENCRYPTION_KEY":"enc-key"
}
client = FivePaisaClient(email=email, passwd=pw, dob=dob,cred=cred)
client.login()
In general it is bad practice to get a value from STDOUT. There are some ways but it's pretty tricky (it's not made for it). And the problem doesn't come from you but from the API which is wrongly designed, it should return a value e.g. True or False (at least) to tell you if you logged in, and they don't do it.
So, according to their documentation it is not possible to know if you're logged in, but you may be able to see if you're logged in by checking the attribute client_code in the client object.
If client.client_code is equal to something then it should be logged in and if it is equal to something else then not. You can try comparing it's value when you successfully login or when it fails (wrong credential for instance). Then you can put a condition : if it is None or False or 0 (you will have to see this by yourself) then it is failed.
Can you try doing the following with a successful and failed login:
client.login()
print(client.client_code)
Source of the API:
# Login function :
# (...)
message = res["body"]["Message"]
if message == "":
log_response("Logged in!!")
else:
log_response(message)
self._set_client_code(res["body"]["ClientCode"])
# (...)
# _set_client_code function :
def _set_client_code(self, client_code):
try:
self.client_code = client_code # <<<< That's what we want
except Exception as e:
log_response(e)
Since this questions asks how to capture "stdout" one way you can accomplish this is to intercept the log message before it hits stdout.
The minimum code to capture a log message within a Python script looks this:
#!/usr/bin/env python3
import logging
logger = logging.getLogger(__name__)
class RequestHandler(logging.Handler):
def emit(self, record):
if record.getMessage().startswith("Hello"):
print("hello detected")
handler = RequestHandler()
logger.addHandler(handler)
logger.warning("Hello world")
Putting it all together you may be able to do something like this:
import logging
from py5paisa import FivePaisaClient
email = "myemailid#gmail.com"
pw = "mypassword"
dob = "mydateofbirth"
cred={
"APP_NAME":"app-name",
"APP_SOURCE":"app-src",
"USER_ID":"user-id",
"PASSWORD":"pw",
"USER_KEY":"user-key",
"ENCRYPTION_KEY":"enc-key"
}
client = FivePaisaClient(email=email, passwd=pw, dob=dob,cred=cred)
class PaisaClient(logging.Handler):
def __init__():
self.loggedin = False # this is the variable we can use to see if we are "logged in"
def emit(self, record):
if record.getMessage().startswith("Logged in!!")
self.loggedin = True
def login():
client.login()
logging.getLogger(py5paisa) # get the logger for the py5paisa library
# tutorial here: https://betterstack.com/community/questions/how-to-disable-logging-from-python-request-library/
logging.basicConfig(handlers=[PaisaClient()], level=0, force=True)
c = PaisaClient()
c.login()

Getting an invalid token on an interpolated string sent from python/jinga2 backend

I'm sending a variable called apiID from a tornado/jinja2 python file to my vuejs template like this:
class SmartAPIUIHandler(BaseHandler):
def get(self, yourApiID):
doc_file = "smartapi-ui.html"
dashboard_template = templateEnv.get_template(doc_file)
dashboard_output = dashboard_template.render(apiID = yourApiID )
self.write(dashboard_output)
then in vuejs I'm interpolating the variable with no problem except it gives me an error
it says: Uncaught SyntaxError: Invalid or unexpected token
I checked on the python handler file and apipID is a string, so I don't see the problem. I'm quite new to python so maybe the answer is more obvious to one of you. I appreciate the help!!
Because of dashboard_output = dashboard_template.render(apiID = yourApiID ), you must have, in your template, something around the code:
this.apiID = {{ apiID }};
Due to the value being not a number but a string, add the 's:
this.apiID = '{{ apiID }}';

python - urllib.request.urlretrieve throws unexpected exception unknown url type: ' '

I am trying to download files using urllib.request.retrieve()
I am using Python 3 and the downloads are successful, but I don't know why it throws exception.
For some reason it throws an exception.
This is the main file:
import os
import urllib.request
zip_file_open = open("urls.txt")
if not os.path.exists('zip'):
os.makedirs('zip')
num=1
true = True
b = true
for i in zip_file_open.read().splitlines():
try:
print(str(i))
#response = urllib.request.urlopen(str(i))
#print(response)
#html = response.read()
urllib.request.urlretrieve(i, "zip/code"+str(num)+".zip")
if(b):
num+=1
b=False
else:
b=true
except Exception as e:
print("Exception: "+str(e))
if(b):
num+=1
b=False
else:
b=true
This is urls.txt:
http://media.wiley.com/product_ancillary/50/11188580/DOWNLOAD/c01_code.zip
http://media.wiley.com/product_ancillary/50/11188580/DOWNLOAD/c02_code.zip
........
http://media.wiley.com/product_ancillary/50/11188580/DOWNLOAD/c25_code.zip
http://media.wiley.com/product_ancillary/50/11188580/DOWNLOAD/c26_code.zip
Here is how I create the txt file:
f = open("urls.txt","w")
k = """http://media.wiley.com/product_ancillary/50/11188580/DOWNLOAD/c"""
k1 = """_code.zip"""
import os
for i in range(26):
if(i<9):
f.write(k+str(0)+str(i+1)+k1+os.linesep)
else:
f.write(k+str(i+1)+k1+os.linesep)
f.close()
Here is the output
http://media.wiley.com/product_ancillary/50/11188580/DOWNLOAD/c01_code.zip
Exception2: unknown url type: ''
http://media.wiley.com/product_ancillary/50/11188580/DOWNLOAD/c02_code.zip
Exception3: unknown url type: ''
http://media.wiley.com/product_ancillary/50/11188580/DOWNLOAD/c03_code.zip
Exception3: HTTP Error 404: Not Found
........
Exception26: unknown url type: ''
http://media.wiley.com/product_ancillary/50/11188580/DOWNLOAD/c26_code.zip
Exception27: unknown url type: ''
I didn't include all the lines of output as they were same. The code is functional but I would like to know if we can remove the exception.
It looks like you have some blank lines in your file, so urllib throws a ValueError exception when you try to fetch '', which is clearly not a url.
You can fix this error if you add a condition in the loop to check for empty strings.
for i in zip_file_open.read().splitlines():
if not i.strip():
continue
...
But this won't work for non-empty strings that are not urls, for example 'not a url'.
A better approach would be to check the url scheme with urlparse.
for i in zip_file_open.read().splitlines():
if not urllib.parse.urlparse(i).scheme:
continue
...

web2py rest api endpoint gives invalid path output

I have made a web2py web application. The api endpoints exposed are as follows.
"/comments[comments]"
"/comments/id/{comments.id}"
"/comments/id/{comments.id}/:field"
"/comments/user-id/{comments.user_id}"
"/comments/user-id/{comments.user_id}/:field"
"/comments/date-commented/{comments.date_commented.year}"
"/comments/date-commented/{comments.date_commented.year}/:field"
"/comments/date-commented/{comments.date_commented.year}/{comments.date_commented.month}"
"/comments/date-commented/{comments.date_commented.year}/{comments.date_commented.month}/:field"
"/comments/date-commented/{comments.date_commented.year}/{comments.date_commented.month}/{comments.date_commented.day}"
"/comments/date-commented/{comments.date_commented.year}/{comments.date_commented.month}/{comments.date_commented.day}/:field"
"/comments/date-commented/{comments.date_commented.year}/{comments.date_commented.month}/{comments.date_commented.day}/{comments.date_commented.hour}"
"/comments/date-commented/{comments.date_commented.year}/{comments.date_commented.month}/{comments.date_commented.day}/{comments.date_commented.hour}/:field"
"/comments/date-commented/{comments.date_commented.year}/{comments.date_commented.month}/{comments.date_commented.day}/{comments.date_commented.hour}/{comments.date_commented.minute}"
"/comments/date-commented/{comments.date_commented.year}/{comments.date_commented.month}/{comments.date_commented.day}/{comments.date_commented.hour}/{comments.date_commented.minute}/:field"
"/comments/date-commented/{comments.date_commented.year}/{comments.date_commented.month}/{comments.date_commented.day}/{comments.date_commented.hour}/{comments.date_commented.minute}/{comments.date_commented.second}"
"/comments/date-commented/{comments.date_commented.year}/{comments.date_commented.month}/{comments.date_commented.day}/{comments.date_commented.hour}/{comments.date_commented.minute}/{comments.date_commented.second}/:field"
"/comments/complaint-id/{comments.complaint_id}"
"/comments/complaint-id/{comments.complaint_id}/:field"
The comments model is as follows
models/db.py
db.define_table(
'comments',
Field('user_id', db.auth_user),
Field('comment_made', 'string', length=2048),
Field('date_commented', 'datetime', default=datetime.now),
Field('complaint_id', db.complaints),
Field('detailed_status', 'string', length=2048),
)
I have been successful in retriving a single comment via the following request
localhost:8000/api/comments/id/1.json
Now I wish to retrieve all the comments. I am not able to figure out how to use /comments[comments] to retrieve all comments.?
I have tried
localhost:8000/api/comments.json
But it gives an output with "invalid path"
I have realized requests such as http://localhost:8000/api/comments/complaint-id/1.json
also give "invalid path" as output.
Please help.
EDIT:
Controllers/default.py
#request.restful()
def api():
response.view='generic.' + request.extension
def GET(*args,**kargs):
patterns='auto'
parser = db.parse_as_rest(patterns,args,kargs)
if parser.status == 200:
return dict(content=parser.response)
else:
raise HTTP(parser.status,parser.error)
def POST(*args,**kargs):
return dict()
return locals()
routes.py in the main web2py folder to change the default application:
routers = dict(
BASE = dict(
default_application='GRS',
)
)
Another observation:
I added another endpoint as below:
def comm():
"""" Comments api substitute"""
rows=db().select(db.comments.ALL) ## this line shows error
# rows = db(db.comments.id > 0).select()
#rows=[[5,6],[3,4],[1,2]]
#for row in rows:
# print row.id
return dict(message=rows)
Even now I am not able to retrieve all comments with "/comm.json". This gives a web2py error ticket which says "need more than 1 value to unpack" on the line "rows=db.select(db.comments.ALL)". Are the above invalid path and this error related in someway?

grails internationalization (i18n)

i work on grails project
def result = "customer"
//(this value is according to returned method parameter,
//it may be customer, company,... & so on)
def messages = "${message(code: 'default.result.${result}', default:'${result}')}"
i need to send a variable inside message code as i mention above
problem: this code appears as
default.result.${result}
that there is no code in message.properties refer to these code
there is default.result.customer ....$ so on
Question: how can i send variable inside message Code?
Try omitting the double quotes (GString) and it should work like the following:
def xxx = "bar"
def m = message(code: "foo.${xxx}", args: ['hello world'])
Results in following message-code
foo.bar
Try:
def messages = message(code: 'default.result.' + result, default: result)
If you want to pass in some values, e.g. a string, you can define your message like this:
default.result.success = Action {0} was successfull.
And resolve your code like this:
def m = message(code: 'default.result.' + result, args: ['delete User'])