ssh connection in python - python

I'm trying to read a text file from a server using ssh from python 3.5. I'm using paramiko to connect to the server but unfortunately, I'm having trouble actually connecting to the server.
this is the code I'm using to connect to the server
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('IP ADDRESS OF THE SERVER', key_filename="/home/user/.ssh/id_ecdsa" ,look_for_keys=True)
but every time I try to connect to the server I'm getting an authentication failed error message, can anyone see what I'm doing wrong here?
Any advice would be appreciated
This is the error I'm getting everytime i connect.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.5/site-packages/paramiko/client.py", line 380, in connect
look_for_keys, gss_auth, gss_kex, gss_deleg_creds, gss_host)
File "/usr/local/lib/python3.5/site-packages/paramiko/client.py", line 603, in _auth
raise saved_exception
File "/usr/local/lib/python3.5/site-packages/paramiko/client.py", line 580, in _auth
allowed_types = set(self._transport.auth_publickey(username, key))
File "/usr/local/lib/python3.5/site-packages/paramiko/transport.py", line 1331, in auth_publickey
return self.auth_handler.wait_for_response(my_event)
File "/usr/local/lib/python3.5/site-packages/paramiko/auth_handler.py", line 208, in wait_for_response
raise e
paramiko.ssh_exception.AuthenticationException: Authentication failed.

You should use your private key to connect to a remote server. Your public key must be already installed in the server side, i.e. it must be listed in ~/.ssh/authorized_keys.
Try first from the command line, and only then use Python/paramiko. Check the permissions of the files/directories if all that fails.

Turns out I simply just forgot to add in the username in the connection string. works perfectly now.

Related

Connecting to Atlas MongoDb using pymongo - ServerSelectionTimeoutError

I'm having trouble connecting to a db I set up in Atlas MongoDB.
I have already read multiple other questions but no answer made my connection work.
I want to point out that I am trying to access it behind a company's proxy (if that has anything to do with it).
My code is this and fails only on the last line where I try to count the documents:
from pymongo import MongoClient
client = MongoClient(
"mongodb+srv://name:pass#iliastrialcluster-1tl2y.azure.mongodb.net/test?retryWrites=true&w=majority&ssl=true&ssl_cert_reqs=CERT_NONE"
)
db = client.get_database('sample_airbnb')
print(db)
listings_and_reviews = db.listingAndReviews
print(listings_and_reviews)
listings_and_reviews.count_documents({})
The error I get is:
Traceback (most recent call last):
File "C:~/mongo_connection1.py", line 11, in <module>
listings_and_reviews.count_documents({})
File "C:~\lib\site-packages\pymongo\collection.py", line 1721, in count_documents
_cmd, self._read_preference_for(session), session)
File "C:~\lib\site-packages\pymongo\mongo_client.py", line 1454, in _retryable_read
read_pref, session, address=address)
File "C:~\lib\site-packages\pymongo\mongo_client.py", line 1253, in _select_server
server = topology.select_server(server_selector)
File "C:~\lib\site-packages\pymongo\topology.py", line 235, in select_server
address))
File "C:~\lib\site-packages\pymongo\topology.py", line 193, in select_servers
selector, server_timeout, address)
File "C:~\lib\site-packages\pymongo\topology.py", line 209, in _select_servers_loop
self._error_message(selector))
pymongo.errors.ServerSelectionTimeoutError: iliastrialcluster-shard-00-00-1tl2y.azure.mongodb.net:27017: timed out,iliastrialcluster-shard-00-02-1tl2y.azure.mongodb.net:27017: timed out,iliastrialcluster-shard-00-01-1tl2y.azure.mongodb.net:27017: timed out
ServerSelectionTimeout error is the client's way of telling you you can't connect to the server. The primary cause of these errors when using MongoDB Atlas is the failure to enable access for the IP address of the node the client is running on.
To verify try connecting using the MongoDB shell mongo using the same connection string. if you get a connection failed then you know it's not a Python problem. Your client code looks OK BTW so I am pretty sure this is what it is.
The connection to the server is lazily evaluated so we don't try to initiate a connection until you make an actual request. In this case the count_documents call. This is why this is the call that generates the error.
#JoeDrumgoole Thanks for your answer. The problem was the proxy after all, after deactivating it the connection works fine. Good to know that the connection to the server is lazily evaluated.

Python mysql connector change host link to ipaddress

I am coming across an issue with mysql connector.
I have an environment that i can't connect from my local machine.
I use simple command for connection:
from mysql.connector import connect
connection = mysql.connector.connect(user='dbuser', database='dbname',
host='amazon_link', password='dbpassword')
This works for all environment except one. And this also works in the server as well where the database lives.
I can access the database using my MySqlWorkbench from local machine. But when i try from my script, i get the following error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/rajatvij/Development/env/lib/python2.7/site-packages/mysql/connector/__init__.py", line 179, in connect
return MySQLConnection(*args, **kwargs)
File "/Users/rajatvij/Development/env/lib/python2.7/site-packages/mysql/connector/connection.py", line 95, in __init__
self.connect(**kwargs)
File "/Users/rajatvij/Development/env/lib/python2.7/site-packages/mysql/connector/abstracts.py", line 719, in connect
self._open_connection()
File "/Users/rajatvij/Development/env/lib/python2.7/site-packages/mysql/connector/connection.py", line 210, in _open_connection
self._ssl)
File "/Users/rajatvij/Development/env/lib/python2.7/site-packages/mysql/connector/connection.py", line 144, in _do_auth
self._auth_switch_request(username, password)
File "/Users/rajatvij/Development/env/lib/python2.7/site-packages/mysql/connector/connection.py", line 177, in _auth_switch_request
raise errors.get_exception(packet)
mysql.connector.errors.ProgrammingError: 1045 (28000): Access denied for user 'dbuser'#'10.0.1.72' (using password: YES)
And the ip address that i get for the host link is different from what mysql connector is showing here as well.
Is there a way to avoid mysql connector to change link to url here, as when i use the link instead of ip address in my Workbench i am able to connect. So i doubt it is an issue related to vpn or security groups. Otherwise i wouldn't be able to connect to database via work bench at all.
Any help would be appreciated. Thanks.
And sorry in case i missed something basic here.
Try to use the global IP address of your server instead of the domain name.
Refer the stackoverflow link for more details:
Remotely connect to MySQL with Python mysql.connector

Using a Python script to establish FTP connection behind FTP proxy

Im trying to connect to an ftp server that is behind ftp proxy.
The proxy server does not require username and password, the ftp server does.
I have searched through several posts:
Proxies in python
How to use urllib2 to access ftp/http server using proxy with authentification
How to connect to ftp server via proxy using ftplib
How to specify an authenticated proxy for a python http connection?
Here is the last version of my code. So far I've figured out that to open the ftp server behind an ftp proxy, the notation ftp://username:password#server can be used. I'm using the urllib2 library to define the proxy server.
import urllib2
proxy_host = '101.11.44.84:8021' # only host name, no scheme (http/ftp)
proxy_handler = urllib2.ProxyHandler({'ftp': proxy_host})
auth = urllib2.FTPHandler()
try:
opener_thru_proxy = urllib2.build_opener(proxy_handler, auth)
except:
logger.exception('build_opener error')
raise
print opener_thru_proxy
try:
conn = opener_thru_proxy.open('ftp://user:password#100.159.66.113')
except:
logger.exception('opener thru proxy error')
raise
print conn.read()
conn.close()
The output of this code yields:
2016-05-23 16:15:28,286 - root - ERROR - opener thru proxy error
Traceback (most recent call last):
File "<string>", line 293, in <module>
File "C:\_Studna\Python\python-2.7.10.amd64\lib\urllib2.py", line 431, in open
File "C:\_Studna\Python\python-2.7.10.amd64\lib\urllib2.py", line 449, in _open
File "C:\_Studna\Python\python-2.7.10.amd64\lib\urllib2.py", line 409, in _call_chain
File "C:\_Studna\Python\python-2.7.10.amd64\lib\urllib2.py", line 1412, in ftp_open
File "C:\_Studna\Python\python-2.7.10.amd64\lib\urllib2.py", line 1434, in connect_ftp
File "C:\_Studna\Python\python-2.7.10.amd64\lib\urllib.py", line 875, in __init__
File "C:\_Studna\Python\python-2.7.10.amd64\lib\urllib.py", line 884, in init
File "C:\_Studna\Python\python-2.7.10.amd64\lib\ftplib.py", line 135, in connect
File "C:\_Studna\Python\python-2.7.10.amd64\lib\socket.py", line 575, in create_connection
URLError: <urlopen error ftp error: [Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond>
It seems that I'm unable to establish the ftp connection with the ftp server.
However, when I use the same set of connection data and use it in Total Commander, the connection works correctly. See the image enclosed Total Commander ftp connection window.

Python mysql connector access denied error

I've read everything possible and I just can't connect to my mysql server. Here is my code. very simple. (I used xxx to hide all the private info. everything else is the way i got it.
import mysql.connector
conn = mysql.connector.connect(user='xxxx',password='xxxxx',host='xxxx',db='xxx',port=3306)
The login info is definitely correct. I tried it in a mysql client and it connected just fine. The MySQL server is hosted on dreamhost. I set the allowable IPs for the db user to wildcard %.%.%.% so anyone could connect.I don't know what else could possibly be wrong. When I try to connect in python i get:
C:\Python33\python.exe D:/Dropbox/python/v2/test.py
Traceback (most recent call last):
File "D:/Dropbox/python/v2/test.py", line 3, in <module>
conn = mysql.connector.connect(user='xxx',password='xxx',host='xxx',db='xxx',port=3306)
File "C:\Python33\lib\site-packages\mysql\connector\__init__.py", line 101, in connect
return MySQLConnection(*args, **kwargs)
File "C:\Python33\lib\site-packages\mysql\connector\connection.py", line 117, in __init__
self.connect(**kwargs)
File "C:\Python33\lib\site-packages\mysql\connector\connection.py", line 383, in connect
self._open_connection()
File "C:\Python33\lib\site-packages\mysql\connector\connection.py", line 350, in _open_connection
self._ssl)
File "C:\Python33\lib\site-packages\mysql\connector\connection.py", line 176, in _do_auth
raise errors.get_exception(packet)
mysql.connector.errors.ProgrammingError: 1044 (42000): Access denied for user 'xxx'#'%.%.%.%' to database 'xxx'
Any help would be greatly appreciated.
You will have to GRANT permissions to the user.
Something like:
GRANT ALL PRIVILEGES ON *.* TO 'user2'#'localhost' IDENTIFIED BY PASSWORD 'xxxxx'

How to send simple email using Python

Before you mark this as a duplicate; I've read the other threads as well. I'm trying to send an email as simple as using the mail() function in php. I simply tried the example from the official python docs. But when I try to connect with the localhost on my linux machine I get:
>>> import smtplib
>>> smtplib.SMTP('localhost')
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/usr/lib/python2.7/smtplib.py", line 251, in __init__
(code, msg) = self.connect(host, port)
File "/usr/lib/python2.7/smtplib.py", line 311, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "/usr/lib/python2.7/smtplib.py", line 286, in _get_socket
return socket.create_connection((host, port), timeout)
File "/usr/lib/python2.7/socket.py", line 571, in create_connection
raise err
error: [Errno 111] Connection refused
I thought this example didn't need an email server to run (just like the php mail() function doesn't need an email-server to run).
Any ideas what I might be doing wrong or how I can get this to send an email? All tips are welcome!
The php mail() function does need a relay to send messages. It defaults to sendmail on Linux machines.
On Windows you have to give it the address of a SMTP server.
In order for any program to send email, you need to connect to a SMTP server. There is no running around that.

Categories

Resources