I have an python error AttributeError: 'module' object has no attribute 'initialize'
I am running Python 2.6.2 on Solaris 10 UNIX and recently installed the pythonldap 2.3.9. The script is very basic, only has these 2 lines. Can anyone tell me why?? Traceback error below.
#!/usr/local/bin/python
import ldap, sys
con = ldap.initialize('ldap://localhost')
Traceback (most recent call last):
File "./myldap.py", line 5, in
con = ldap.initialize('ldap://localhost')
AttributeError: 'module' object has no attribute 'initialize'
Regards,
Jenny
Did you name a file in the current directory ldap.py that is shadowing the one that you want?
Many people are giving much more complicated solutions... Simply put, the pip installation of the ldap module doesn't work. You need to install the python-ldap package from apt or yum. Note that the deb package is now named python3-ldap, after the deprecation of python 2.
An easy way to tell if the ldap you're importing is the right one is to print ldap.__file__, which prints the full path to the module file (usually a '.pyc'). If it's not the one installed in the location you are expecting, this is your problem, as Mike Graham suggested.
I did the ldap connection successfully. How to go:
1.I have python v 3.7.2
2.Install python-ldap:For this I tried "pip install python-ldap" but it not worked
for me on windows machine so I use the alternate below.
3.For installing ldap go here:https://www.lfd.uci.edu/~gohlke/pythonlibs/#python-ldap
and download python_ldap‑3.1.0‑cp37‑cp37m‑win_amd64.whl
4.Now move to the download directory and run "pip install
python_ldap‑3.1.0‑cp37‑cp37m‑win_amd64.whl"
Now open python shell and check "import ldap" if you are getting no error means you are done.
This is the sample code:
#Resource of code :https://gist.github.com/ibeex/1288159
import ldap
def check_credentials(username, password):
"""Verifies credentials for username and password.
Returns None on success or a string describing the error on failure
# Adapt to your needs
"""
LDAP_SERVER = 'xxx'
# fully qualified AD user name
LDAP_USERNAME = '%s#spi.com' % username
# your password
LDAP_PASSWORD = password
base_dn = 'DC=spi,DC=com'
ldap_filter = 'userPrincipalName=%s#spi.com' % username
attrs = ['memberOf']
try:
# build a client
ldap_client = ldap.initialize(LDAP_SERVER)
# perform a synchronous bind
ldap_client.set_option(ldap.OPT_REFERRALS,0)
ldap_client.simple_bind_s(LDAP_USERNAME, LDAP_PASSWORD)
except ldap.INVALID_CREDENTIALS:
#print("wron")
ldap_client.unbind()
return 'Wrong username or password'
except ldap.SERVER_DOWN:
#print("down")
return 'AD server not awailable'
# all is well
# get all user groups and store it in cerrypy session for future use
ab = str(ldap_client.search_s(base_dn,
ldap.SCOPE_SUBTREE, ldap_filter, attrs)[0][1]['memberOf'])
#print("ab"+ab)
ldap_client.unbind()
return 'success'
if __name__ == "__main__":
u="chirag"
p="secred"
print(check_credentials(u,p))
You can get that error if you're somehow picking up the "ldap.py" from sos/plugins/ instead of the ldap package itself. Make sure the "python-ldap" package is actually installed...
I guess you have installed "pip install ldap"! In this module "initialize" or "open" are not present.
Uninstall that "ldap" by "pip uninstall ldap" and then try "yum install python-ldap". And run the same code.
Print the "con".
open does not exist anymore in version 3.x of python-ldap.
I fixed it by forcing the installation of an older version :
pip install python-ldap==2.4.13
Related
I've run into this issue while using the jira library for python. Despite setting the appropriate parameters for basic auth, I get the following:
Exception ignored in: <bound method Magic.del of <magic.Magic object at 0x7f2a4e5ff128>>
Traceback (most recent call last):
File "/home/keckj/.local/lib/python3.6/site-packages/magic.py", line 129, in del
if self.cookie and magic_close:
AttributeError: 'Magic' object has no attribute 'cookie'
Here's a quick snippet:
from jira import JIRA
user = 'xxxx.xxxxx#xxxxxx.com'
apikey = 'xxxxxxxxxxxxxxxxxxxxx'
jira_server = 'https://xxxxxxxxxx.jira.com'
options = {'server': jira_server}
jira = JIRA(options, basic_auth=(user,apikey))
issue = jira.issue("KEY-123")
issue_summary = issue.fields.summary
issue_description = issue.fields.description
print('JIRA ISSUE SUMMARY: %s' %str(issue_summary))
print('JIRA ISSUE DESCRIPTION: %s' %str(issue_description))
I've dug in a few directions via Google but been coming up short:
https://github.com/Linaro/jipdate/issues/30
https://github.com/ahupp/python-magic/issues/47
Python attributeError on __del__
https://github.com/ahupp/python-magic/pull/222
I found the answer buried at bottom of https://github.com/ahupp/python-magic/pull/222:
Apparently python-jira expects the filemagic python package, which takes a flags parameter, but for some reason our environment had your python-magic package, which expects different parameters.
Direct link: https://github.com/ahupp/python-magic/pull/222#issuecomment-675354824
To resolve this, I ran pip install filemagic and voila, no further exceptions.
I tried the "pip install filemagic", but it didn't fix it. It looks like the python-magic module is still installed, and getting picked up. However, another library I use, thehive4py lists python-magic as a dependancy.
You have to also uninstall python-magic at both the system (sudo) and user level. "pip3 uninstall python-magic". But, as stated before, it might/will break other libraries.
Why would someone think it is a good idea to have pip modules with conflicting names? Then, have one throw an error due to poor programing practices. jeesh.
I am looking to send a few items to zabbix using Zabbix-Sender function of pyzabbix. As a test I am running the below code -
from pyzabbix import ZabbixMetric, ZabbixSender, ZabbixResponse
metrics = []
m= ZabbixMetric('mme01', 'TEST', 20)
metrics.append(m)
ZabbixSender('10.46.224.5').send(metrics)
I made this snippet after reading the document - https://py-zabbix.readthedocs.io/en/latest/sender.html
When I run the snippet I get the error -
AttributeError: 'ConnectionRefusedError' object has no attribute 'msg'
I have verified IP connectivity
Can Anyone help ?
there is a mess in modules names.
it seems you call 'other' pyzabbix module who has not needed methods.
first, remove all zabbix-related modules:
pip list | grep zabbix; pip uninstall ...
and then install pyzabbix:
pip install py-zabbix.
this should help.
UPDATED:
I dug deeper and figured out that the AttributeError: 'ConnectionRefusedError' object has no attribute 'msg' exception caused by old module version bug, which has been fixed here. update it with pip or manually.
new bug I have faced is [Errno 8] nodename nor servname provided, or not known caused by socket lib and can be fixed pointing to zabbix server/proxy IP address instead of DNS name
I decided to bypass the module - pyzabbix and decided to use the raw zabbix sender utility. Works great.
For other folks my solution relies on a file with values that need to be sent to zabbix.
Sample file -
"mme01" TEST 1544729668 44
The use the utility -
/opt/zabbix-proxy/bin/zabbix_sender -vv -z 10.43.X.X -T -i mme_file.txt
Replace with path of your zabbix_sender and the zabbix server IP.
I had the same issue on some machines of mine. At that time I refactored my code to use zabbix_sender and it worked great.
After some time I found out the issue was related to pip repository corruption. I ended up reinstalling all the packages with this option:
pip install --ignore-installed <package>
apparently the issue was fixed, but I still have no idea why it occurred on some manchines and not in anothers.
I am trying to use the speedtest-cli api. Copied part of the code from official wiki (and removed unused stuff):
import speedtest
s = speedtest.Speedtest()
s.get_best_server()
s.download()
In python console I get everything ok:
>>> import speedtest
>>> s = speedtest.Speedtest()
>>> s.get_best_server()
{HIDDEN}
>>> s.download()
37257579.09084724
But when I create .py file and run it I get:
AttributeError: module 'speedtest' has no attribute 'SpeedTest'
Thanks
As mentioned in the comments, you have a file with the same name and it is conflicting with the import. Since you have moved the file, restarting the console should work.
The code below will also extract the results into a dictionary and make it possible to access the results.
import speedtest
s = speedtest.Speedtest()
s.get_best_server()
s.download()
s.upload()
res = s.results.dict()
print(res["download"], res["upload"], res["ping"])
I faced the same issue because I had installed both speedtest and speedtest-cli.
Using pip uninstall speedtest worked for me.
I faced the same issue because the name of my file was speedtest. When I change the name to something new. It works fine for me.
import speedtest
wifi = speedtest.Speedtest()
print("Wifi Download Speed is ", wifi.download())
print("Wifi Upload Speed is ", wifi.upload())
Ok Here is the Solution to this Problem
1-uninstall speedtest and speedtest-cli if you have both installed
2- install only speedtest-cli pip install speedtest-cli this will install the package in the main python environment
3-CTRL+P select interpreter then select your main python not any environment
4-it will work fine
Reason for this error
(you install the package in your main python environment and you usually open your IDE and run a virtual environment)
Try checking speedtest is imported properly
import speedtest
print(dir(speedtest))
it should display properties of speedtest
I found a code which i need. It is from this link : How to install a package using the python-apt API
#!/usr/bin/env python
# aptinstall.py
import apt
import sys
pkg_name = "libjs-yui-doc"
cache = apt.cache.Cache()
cache.update() # error is in this line
pkg = cache[pkg_name]
if pkg.is_installed:
print "{pkg_name} already installed".format(pkg_name=pkg_name)
else:
pkg.mark_install()
try:
cache.commit()
except Exception, arg:
print >> sys.stderr, "Sorry, package installation failed [{err}]".format(err=str(arg))
However i can't make it work. I searched about the problem on the web. It is said that there should be no package manager,apt,pip etc active in order to work with this code. However, no package manager,apt,pip etc. is open in my computer. I thought that when computer starts, some package manager can be active. So i typed
ps -aux
in terminal and look at the active processes, but i didn't see any active process related to package manager(i'm not %100 sure about this, because any process i don't know can be related to package manager.But how could i know it?) To sum up,i started the computer and opened only terminal. Then i typed python aptinstall.py and hit enter. I take the following error :
Traceback (most recent call last):
File "aptinstall.py", line 7, in <module>
cache.update()
File "/usr/lib/python2.7/dist-packages/apt/cache.py", line 397, in update
raise LockFailedException("Failed to lock %s" % lockfile)
apt.cache.LockFailedException: Failed to lock /var/lib/apt/lists/lock
I delete the lock by giving the command in terminal :
sudo rm /var/lib/dpkg/lock
It didn't work too.
How can i solve this problem? Any idea will be appreciated.
Please try looking for update-manager in ps. It runs automatically on a periodic basis, so it may be locking the apt db.
There are three different reasons which cause this error.
1 - As i mentioned earlier, if any package manager is runnning(for example;pip,apt-get,synaptic,etc), it gives the error.
2 - If you are using your ubuntu in a virtual machine, this causes the same error.
3 - If you are running your program without root privileges, this causes the same error. For example ,if you are running your program with "python aptinstall.py" you get the error, running the program with "sudo python aptinstall.py" is the correct one.
I'm getting the following error message when I try to open up a connection to a postgres database. Perhaps it's related to OpenSSL, but I can't understand the error message. Can anyone help?
>>> import psycopg2
>>> conn = psycopg2.connect(host = '', port = , dbname
= '', user = '', password = '')
Auto configuration failed
12848:error:02001015:system library:fopen:Is a directory:.\crypto\bio\bss_file.c
:169:fopen('D:/Build/OpenSSL/openssl-1.0.1h-vc9-x64/ssl/openssl.cnf','rb')
12848:error:2006D002:BIO routines:BIO_new_file:system lib:.\crypto\bio\bss_file.
c:174:
12848:error:0E078002:configuration file routines:DEF_LOAD:system lib:.\crypto\co
nf\conf_def.c:199:
One problem that I can think of is that your installation may not have been linked/built properly to use openssl. If you haven't tried the packages listed in the docs yet, maybe you could give it a try.
When I look at the docs:
Microsoft Windows:
Jason Erickson maintains a packaged Windows port of Psycopg with installation executable. Download. Double click. Done.
So you could try to install it from there. Or you can try the pip-friendly windows-friendly (note: I didn't try it myself) psycopg2-windows package.