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.
Related
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.
This question already has answers here:
Multi-factor authentication (password and key) with Paramiko
(3 answers)
Closed last year.
Trying to use pysftp to pull files from an sFTP server that requires both ssh key & password for authentication without much luck. Can use pysftp with just key and just password, but it breaks when I attempt to use both. Hoping someone has some experience with this. Open to using a different library if that works better.
Error output is:
paramiko.ssh_exception.BadAuthenticationType: Bad authentication type; allowed types: ['publickey']
import pysftp
connection_host = '1.1.1.1'
connection_user = 'username'
connection_password = 'password'
connection_private_key = '/path/to/key'
connection_dir='/dir/on/remote/host'
with pysftp.Connection(host=connection_host, username=connection_user, password=connection_password, private_key=connection_private_key) as sftp:
files = sftp.listdir(remotepath=connection_dir)
for file in files:
print("found the following file: {}".format(file))
with sftp.cd(connection_dir):
sftp.get(file)
Working code if anyone runs into the same issue:
connection_host = '0.0.0.0'
connection_user = 'username'
connection_password = 'password'
connection_private_key = '/path/to/key.pem'
connection_dir='/remote/path'
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy)
ssh.connect(connection_host, username=connection_user, password=connection_password, key_filename=connection_private_key)
sftp_client = ssh.open_sftp()
files = sftp_client.listdir(connection_dir)
sftp_client.chdir(connection_dir)
for file in files:
print("found the following file {}".format(file))
sftp_client.get(file,file)
if sftp_client:
sftp_client.close()
if ssh:
ssh.close()
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')
I have trying to make a SFTP connection using a proxy
and print out the files in the SFTP directory
import pysftp
myHostname = "some.hostname.com"
myUsername = "test"
myPassword = "password"
myProxyHost = "10.10.10.10"
myProxyPort = "1010"
with pysftp.Connection(
host=myHostname,
username=myUsername,
password=myPassword,
proxy=myProxyHost,
proxyport=myProxyPort,
) as sftp:
print("Connection succesfully stablished ... ")
# Switch to a remote directory
sftp.cwd("/test/folder")
directory_structure = sftp.listdir_attr()
# Print data
for attr in directory_structure:
print(attr.filename, attr)
but I am getting a error of 'TypeError: init() got an unexpected keyword argument 'proxy''
could someone show me how to use proxy to make a successful connection.
Based on pysftp.Connection()'s documentation, it does not support proxy or proxyport parameters.
You may have better luck using the underlying Paramiko SFTPClient class – there's a gist over here that seems to have an explanation about proxying with Paramiko.
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