How to fix "LDAPInvalidPortError: Port must be an integer" - python

I'm trying to connect to a server using LDAP. I've gotten the script to work on a test server that didn't use a specific port number. When trying to connect to our Dev-System, which uses a specific port I receive the following error:
File "site-packages\ldap3\core\server.py", line 117, in__init__
ldap3.core.exceptions.LDAPInvalidPortError: port must be an integer
[7836] Failed to execute script ldap_query
In the past we used python-ldap which didn't have an issue with a specified port in the ldap.initialize('LDAP://cd-dir...net/(Port)') command. The piece of code that generates the error can be seen below.
def ldap_connect(address, dn, password)
server = Server(address)
try:
conn = Connection(server, dn, password, auto_bind = True)
print('Authentication Successful')
print(conn.extend.standard.who_am_i())
except: LDAPBindError as err:
print(LDAPBindError)
ldap_connect('LDAP://cd-dir-cd-test....net:port/dc=cd...dc=com', 'user', 'password')
To solve the issue I tried taking the port number out of the address and instead put it in the following way:
server = Server(address, port = XXX)
That solved the "port must be an integer" error. However, that didn't solve the problem. The new error that I'm receiving is:
File "site-packages\ldap3\core\connection.py", line 325, in__init__
File "site-packages\ldap3\core\connection.py", line 340, in do_auto_bind
File "site-packages\ldap3\strategy\sync.py", line 56, in open
File "site-packages\ldap3\strategy\base.py", line 151, in open
ldap3.core.exceptions.LDAPSocketOpenError: invalid server address
[5976] Failed to execute script ldap_query
How can I solve this issue? Is there another way to set the port that I don't know of?
Best wishes,

You're passing an ldap:// URI to ldap_connect, but it looks like the ldap3.Server class expects an hostname or address. That is, you're currently trying to do this:
server = Server('ldap://cd-dir-cd-test.example.net:port')
When what you need is:
server = Server('cd-dir-cd-test.example.net', port=port)
And of course port must be an integer, not a string. You can use the ldap3.utils.uri.parse_uri method to extract the information you want from an ldap URI:
from ldap3 import Server, Connection
from ldap3.utils.uri import parse_uri
def ldap_connect(uri, dn, password):
parsed = parse_uri(uri)
server = Server(parsed['host'], use_ssl=parsed['ssl'], port=parsed['port'])
conn = Connection(server, dn, password, auto_bind = True)
print('Authentication Successful')
print(conn.extend.standard.who_am_i())
return conn
conn = ldap_connect('LDAP://cd-dir-cd-test....net:port/dc=cd...dc=com',
'user', 'password')

Related

ValueError: No password or public key available

I'm trying to connect to a remote MySQL database through an SSH Tunnel and deploying my code to Streamlit. When I try to do it, I get this error:
File "/home/appuser/venv/lib/python3.9/site-packages/sshtunnel.py", line 966, in __init__
(self.ssh_password, self.ssh_pkeys) = self._consolidate_auth(
File "/home/appuser/venv/lib/python3.9/site-packages/sshtunnel.py", line 1169, in _consolidate_auth
raise ValueError('No password or public key available!')
ValueError: No password or public key available!
I've tried a lot of things, from updating my SSH keys to my server and github to changing my code.
The code I have for the SSH - MySQL section looks like this:
import MySQLdb as db
from sshtunnel import SSHTunnelForwarder
def query(q):
with SSHTunnelForwarder(
ssh_address_or_host=("host_ip"),
ssh_username=("host_username"),
ssh_pkey=("path_to_private_sshkey"),
remote_bind_address=("private_host_ip", "host_port")
) as server:
conn = db.connect(
host="localhost",
port=server.local_bind_port,
user="db_username",
passwd="db_password",
db="db_database"
)
return pd.read_sql_query(q, conn)
I appreciate any help you can give me.
conn = db.connect(host="localhost"),
port=server.local_bind_port,
user=("db_username"),
passwd=("db_password"),
db=("db_database")
Because you have a closing parentheses on the first line, only the host argument is being passed to the db.connect() function. And so the function is complaining that it doesn't have a password, username, etc.
The other lines are creating plain local variables.

SSH Tunnel to MariaDB

I've looked at several very similar examples, but I'm doing something wrong...probably because I'm mixing up local or remote binding addresses or well, not sure. I've yet to find a document that can describe what each is supposed to be to a newb like me.
I have a raspberry pi in a robot which has MariaDB installed. I can connect to the server from my PC with SQL Workbench.
I have a second Pi that needs a python script that can send data to the first pi...
IP Addresses, names and passwords have been changed to protect the innocent, but the whole thing is a closed network anyways.
import mysql.connector
import sshtunnel
_host = Robot's IP Address
_ssh_port = 22
_username = Robot user login
_password = Robot Password
_remote_bind_address = Robot's IP Address
_remote_mysql_port = 3308
_local_bind_address = Second Pi's IP Address
_local_mysql_port = 3308
_db_user = Database User Name
_db_password = Database Password
_db_name = "joycap"
with sshtunnel.SSHTunnelForwarder(
(_host, _ssh_port),
ssh_username=_username,
ssh_password=_password,
remote_bind_address=(_remote_bind_address, _remote_mysql_port),
local_bind_address=(_local_bind_address,_local_mysql_port)
) as tunnel:
connection = mysql.connector.connect(
user=_db_user,
passwd=_db_password,
host=_local_bind_address,
database=_db_name,
port=_local_mysql_port)
Here's the error I'm current getting...
pi#raspberrypi:~ $ python dbtest1.py
2018-04-05 06:11:42,262| ERROR | Secsh channel 0 open FAILED: Connection refused: Connect failed
2018-04-05 06:11:42,277| ERROR | Could not establish connection from ('Second Pi's IP Address', 3308) to remote side of the tunnel
Traceback (most recent call last):
File "dbtest1.py", line 29, in <module>
port=_local_mysql_port)
File "/usr/local/lib/python2.7/dist-packages/mysql/connector/__init__.py", line 184, in connect
return MySQLConnection(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/mysql/connector/connection.py", line 100, in __init__
self.connect(**kwargs)
File "/usr/local/lib/python2.7/dist-packages/mysql/connector/abstracts.py", line 733, in connect
self._open_connection()
File "/usr/local/lib/python2.7/dist-packages/mysql/connector/connection.py", line 241, in _open_connection
self._do_handshake()
File "/usr/local/lib/python2.7/dist-packages/mysql/connector/connection.py", line 108, in _do_handshake
packet = self._socket.recv()
File "/usr/local/lib/python2.7/dist-packages/mysql/connector/network.py", line 248, in recv_plain
raise errors.InterfaceError(errno=2013)
mysql.connector.errors.InterfaceError: 2013: Lost connection to MySQL server during query
Would appreciate any advice! Would think someone would have made a video on doing this by now :)
Regards,
Matt
Finally worked it out through trial and error.
_host = "192.168.8.1" #Server where database is hosted
_ssh_port = 22 #ssh port
_username = "pi" #user name to host server
_password = "raspberry" #password to host server
_remote_bind_address = "127.0.0.1" #local connection IP to db on host(should probably not change)
_remote_mysql_port = 3306
_local_bind_address = "0.0.0.0" #local bind address(should probably not change)
_local_mysql_port = 3306
_db_user = "databaseuser"
_db_password = "databasepass"
_db_name = "databasename"

Cannot acquire connection to Neo4j database

I am trying to connect to my Neo4j graph database server from a new machine. I can successfully connect from an older machine but do not wish to use the older one anymore.
I have reduced the problem to a simple script that returns an exception:
from neo4j.v1 import GraphDatabase, basic_auth
auth = basic_auth("username","password")
session = GraphDatabase.driver("bolt://remote.server:7687",auth=auth).session()
statement = """MATCH (a:Protein)
WHERE a.name={name}
RETURN a.Accession"""
tx = session.begin_transaction()
record = tx.run(statement,{'name':"ARCH_HUMAN"}).single()
print record['a.Accession']
session.close()
And the error message is:
File "Test.py", line 10, in <module>
tx = session.begin_transaction()
File "/home/username/anaconda2/lib/python2.7/site-packages/neo4j/v1/api.py", line 432, in begin_transaction
self._connect()
File "/home/username/anaconda2/lib/python2.7/site-packages/neo4j/v1/api.py", line 269, in _connect
self._connection = self._acquirer(access_mode)
File "/home/username/anaconda2/lib/python2.7/site-packages/neo4j/v1/direct.py", line 52, in acquire
raise ServiceUnavailable("Cannot acquire connection to {!r}".format(self.address))
neo4j.exceptions.ServiceUnavailable: Cannot acquire connection to Address(host='remote.server', port=7687)
Port 7687 is open (confirmed via netstat -tulpn and iptables -L), and neo4j is configured to listen to 0.0.0.0:7687. In addition, .neo4j/known_hosts contains an entry for host 0.0.0.0
What's strange is that I get a different error message (neo4j.exceptions.AuthError) if I break the authentication by using an incorrect password. So the connection is being made to check the password, but still I cannot connect with the correct auth.
What's going on?
I too had the same issue and turns out the driver was the issue.
I did some experiments and found out that the last driver that it works for is neo4j-driver==v1.1.0 but the next version neo4j-driver==v1.2.0 it stops working for some reason.
Try uncomment dbms.connectors.default_listen_address=0.0.0.0 And check this
# Bolt connector
dbms.connector.bolt.enabled=true
dbms.connector.bolt.tls_level=OPTIONAL
dbms.connector.bolt.listen_address=:7687
# HTTP Connector. There must be exactly one HTTP connector.
dbms.connector.http.enabled=true
dbms.connector.http.listen_address=:7474
# HTTPS Connector. There can be zero or one HTTPS connectors.
dbms.connector.https.enabled=true
dbms.connector.https.listen_address=:7473

AttributeError: 'str' object has no attribute 'public_blob'

I'd like to get a file onto my raspberry pi from my google cloud compute engine, but I get the following error:
File "/usr/local/lib/python2.7/dist-packages/paramiko/auth_handler.py", line 212, in wait_for_response
raise e
AttributeError: 'str' object has no attribute 'public_blob'
What does this error message mean?
Thanks in advance!
python file:
import paramiko
hostname = '43.123.231.212'
password = 'passw'
username = 'dosop'
port = 22
gc_path='/home/do//assets/locations.txt'
remotepath='/home/pi/ada.txt'
t = paramiko.Transport((hostname, 22))
t.connect(username=username, password=password, pkey="/home/pi/dos/priv_key"
sftp = paramiko.SFTPClient.from_transport(t)
sftp.get(gc_path, remotepath)
The parameter pkey, much like hostkey, expects a value of type PKey. But you seem to be providing a string to it. You can get a PKey object out of your private key file by creating an object from paramiko.RSAKey. The following should help:
import paramiko
hostname = '43.123.231.212'
password = 'passw'
username = 'dosop'
port = 22
gc_path='/home/do//assets/locations.txt'
remotepath='/home/pi/ada.txt'
pk = paramiko.RSAKey.from_private_key(open('/home/pi/dos/priv_key'))
t = paramiko.Transport((hostname, 22))
t.connect(username=username, password=password, pkey=pk)
sftp = paramiko.SFTPClient.from_transport(t)
sftp.get(gc_path, remotepath)
Please note that this assumes you're working with rsa keys; hence the use of paramiko.RSAKey.
Also, please keep in mind that if your private key file has a password, you will need to provide the password as a second argument to the function paramiko.RSAKey.from_private_key, like the following:
pk = paramiko.RSAKey.from_private_key(open('/home/pi/dos/priv_key'), 'password')
I hope this helps.

how can i validate username password for mongodb authentication through pymongo?

I am refering to the http://api.mongodb.org/python/current/examples/authentication.html site for authentication mechanism examples. I have created a User administrator and using its credentials I created a user for my 'reporting' database. Now i need to access the same through pymongo using the username and password. I tried the following commands in python shell. Is this the right way as my authentication is failing.
from pymongo import MongoClient
client = MongoClient('localhost')
client.reporting.authenticate('reportsUser', '123456', mechanism='MONGODB-CR')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/dist-packages/pymongo/database.py", line 746, in authenticate
self.connection._cache_credentials(self.name, credentials)
File "/usr/lib/python2.7/dist-packages/pymongo/mongo_client.py", line 441, in _cache_credentials
auth.authenticate(credentials, sock_info, self.__simple_command)
File "/usr/lib/python2.7/dist-packages/pymongo/auth.py", line 214, in authenticate
auth_func(credentials[1:], sock_info, cmd_func)
File "/usr/lib/python2.7/dist-packages/pymongo/auth.py", line 194, in _authenticate_mongo_cr
cmd_func(sock_info, source, query)
File "/usr/lib/python2.7/dist-packages/pymongo/mongo_client.py", line 607, in __simple_command
helpers._check_command_response(response, None, msg)
File "/usr/lib/python2.7/dist-packages/pymongo/helpers.py", line 147, in _check_command_response
raise OperationFailure(msg % errmsg, code)
pymongo.errors.OperationFailure: command SON([('authenticate', 1), ('user', u'reportsUser'), ('nonce', u'f8158a24f1c61650'), ('key', u'14cea216c54b93bae20acd2e076bb785')]) failed: auth failed
As an FYI, you can use the URI string format as well. The pseudocode looks like this:
pymongo.MongoClient('mongodb://user:password#server:port/')
Here's a simple connection code block with auth:
import pymongo
conn = pymongo.MongoClient('mongodb://root:pass#localhost:27017/')
db = conn['database']
coll = db['collection']
There are more options for the query string here: http://docs.mongodb.org/manual/reference/connection-string/
Hope that helps = looks like you already have it though. Happy coding!!
Just adding more to provided solutions.
I have been using as URI connection string and credentials being provided as f string it helps to reduce number of lines. One thing to note is about special characters in password where we convert using urllib package as shown below.
import urllib.parse
from pymongo import MongoClient
host = "localhost"
port = 27017
user_name = "myuser"
pass_word = "Pass#123"
db_name = "mydb" # database name to authenticate
# if your password has '#' then you might need to escape hence we are using "urllib.parse.quote_plus()"
client = MongoClient(f'mongodb://{user_name}:{urllib.parse.quote_plus(pass_word)}#{host}:{port}/{db_name}')
It's worked for me.
Here you can connect mongodb to python by using authentication username and password.
import pymongo
DATABASE_NAME = "your_database_name"
DATABASE_HOST = "localhost"
DATABASE_USERNAME = "database_username"
DATABASE_PASSWORD = "database_password"
try:
myclient = pymongo.MongoClient( DATABASE_HOST )
myclient.test.authenticate( DATABASE_USERNAME , DATABASE_PASSWORD )
mydb = myclient[DATABASE_NAME]
print("[+] Database connected!")
except Exception as e:
print("[+] Database connection error!")
raise e
By default Mongodb uses 27017 port

Categories

Resources