Getting "socket.error: [Errno 61] Connection refused" python paramiko - python

Getting error connection refused error when trying to connect to the host to copy a local file to the host server. Don't have any issue connecting to the server remotely though.
host = "9.29.22.222"
username = "XXX"
password = "XXX"
local_path = "/Users/samuelhii/Desktop/file.txt"
remote_path = "C:\Program Files (x86)\file.txt"
s = paramiko.SSHClient()
s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
s.connect(host,22,username,password)
sftp = s.open_sftp()
sftp.put(local_path,remote_path)

The connection was refused by the server. This can be caused by several reasons not related to Python programming:
a firewall
the SSH service is configure not to take requests from your IP
bad host ip
… (many more)
Check if you can use the normal SSH client to connect with this host/user/password combination.

Related

Cannot establish SSL connection with FTP using certfile (python)

I'm trying to establish a connection with a FTP server using ftplib.
I received two files, a certificate with .crt extension and a certificate in PEM format (RSA KEY + Certificate).
I'm using the certificate in PEM format to create a context using the following code:
import ssl
from ftplib import FTP_TLS
ssl_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
ssl_context.load_cert_chain('./certificate3')
ftps = FTP_TLS(context = ssl_context)
ftps.connect(host, porta)
ftps.login(user = user, passwd = pwd)
ftps.prot_p()
ftps.nlst()
If I remove the last command (nlst) I receive the response: '230 Logged on'.
Therefore when I try to extract list of documents inside the FTP with nlst() command I receive an error message:
TimeoutError: [WinError 10060] A connection attempt failed because the connected component did not respond
correctly after a period of time or the established connection has failed
because the connected host did not respond
Does anybody know what is wrong and how to fix the code in order to establish the connection?
I could establish connection to FTP server with WinSCP.
Through WinSCP I can run an script to synchronize the server with my local directory. Below you can find the command:
option batch abort
option confirm off
open ftp://user:password#hostserver:port -hostkey="SHA256 KEY"
synchronize local local_path remote_path
exit
This command must be in .txt file, and through a .bat file this command is executed.
Hope I can help other with the same issue.

Connect to Proxy (SOCKS) Database in python

I am trying to connect to a database that needs proxy (socks) to be able to connect, if I use the proxy connection manually, I can connect, but I need to make the script connect to the proxy (socks) of the machine to make this SELECT
SCRIPT
import socket
import socks
import requests
import pymssql
socks.set_default_proxy(socks.SOCKS5, "138.34.133.155", 1080, True, 'user','password')
socket.socket = socks.socksocket
server = '172.43.56.89'
username = 'user'
password = 'password'
database = 'dbname'
conn = requests.get(pymssql.connect(host=server,user=username,password=password,database=database))
cursor = conn.cursor()
cursor.execute("SELECT column FROM table")
row = cursor.fetchall()
conn.close()
for i in row:
print(i)
OUTPUT
Traceback (most recent call last): File "connection.py", line 15, in
conn = requests.get(pymssql.connect(host=server,user=username,password=password,database=database))
File "src\pymssql.pyx", line 642, in pymssql.connect
pymssql.OperationalError: (20009, 'DB-Lib error message 20009,
severity 9:\nUnable to connect: Adaptive Server is unavailable or does
not exist (172.43.56.89:1433)\nNet-Lib error during Unknown error
(10060)\n')
I think an option is to mount a local tunnelling sock with port forwarding, to map your database port and act as if your server where a localhost one.
It's really efficient if you're running your python script on a Unix computer.
Something like this system call (for a 3306 mariaDB) :
ssh -L 3306:localhost:3306 user#x.x.x.x
First, your run SSH, then, you tell him to enable a port forwarding from the 3306 port to the localhost:3306 port of the server you connect through user#IP.
With this, every query from your local machine:3306 will by send to your MariaDB:3306 server, allowing you to use it as if you where on the server.
If you do not want to hack into pymssql source code, there're external tools that redirect all TCP traffic over the socks proxy, such as FreeCap for Windows, RedSocks for Linux and Proximac for macOS.

Translate Oracle SQL Developer SSH Host w/ Local Port Forward Connection to Python

I'm trying to create a Python connection to a remote server through an SSH Jump Host (one I've successfully created in Oracle SQL Developer) but can't replicate in Python. Can connect to SSH Host successfully but fail to forward the port to the remote server due to timeout or error opening tunnels. Safe to assume my code is incorrect rather than server issues. Also need a solution that doesn't use the "with SSHTunnelForwarder() as server:" approach because I need a continuous session similar to OSD/cx_Oracle session rather than a batch processing function.
Similar examples provided here (and elsewhere) using paramiko, sshtunnel, and cx_Oracle haven't worked for me. Many other examples don't require (or at least clearly specify) separate login credentials for the remote server. I expect the critical unclear piece is which local host + port to use, which my SQL Developer connection doesn't require explicitly (although I've tried using the ports OSD chooses, not at the same time).
Closest match I think was best answer from paramiko-port-forwarding-around-a-nat-router
OSD Inputs
SSH Host
- host = proxy_hostname
- port = proxy_port = 22
- username = proxy_username
- password = proxy_password
Local Port Forward
- host = remote_hostname
- port = remote_port = 1521
- automatically assign local port = True
Connection
- username = remote_username
- password = remote_password
- connection type = SSH
- SID = remote_server_sid
Python Code
i.e., analogous code from paramiko-port-forwarding-around-a-nat-router
import paramiko
from paramiko import SSHClient
# Instantiate a client and connect to the proxy server
proxy_client = SSHClient()
proxy_client.connect(
proxy_hostname,
port=proxy_port,
username=proxy_username,
password=proxy_password)
# Get the client's transport and open a `direct-tcpip` channel passing
# the destination hostname:port and the local hostname:port
transport = proxy_client.get_transport()
dest_addr = (remote_hostname,remote_port)
local_addr = ('localhost',55587)
channel = transport.open_channel("direct-tcpip", dest_addr, local_addr)
# Create a NEW client and pass this channel to it as the `sock` (along
# with whatever credentials you need to auth into your REMOTE box
remote_client = SSHClient()
remote_client.connect(
'localhost',
port=55587,
username=remote_username,
password=remote_password,
sock=channel)
Rather than a connection to the remote server I get
transport.py in start_client()
SSHException: Error reading SSH protocol banner
Solution
Finally figured out a solution! Analogous to OSD's automatic local port assignment and doesn't require SSHTunnelForwarder's with statement. Hope it can help someone else- use the question's OSD input variables with...
from sshtunnel import SSHTunnelForwarder
import cx_Oracle
server=SSHTunnelForwarder(
(proxy_hostname,proxy_port),
ssh_username=proxy_username,
ssh_password=proxy_password,
remote_bind_address=(remote_hostname,remote_port))
server.start()
db=cx_Oracle.connect('%s/%s#%s:%s/%s'%(remote_username,remote_password,'localhost',server.local_bind_port,remote_server_sid))
# do something with db
server.close()

Ftplib ConnectionRefusedError: [Errno 111] Connection refused (python 3.5)

I have a script that should connect to a FTP
from ftplib import FTP
with FTP('IP') as ftp:
ftp.login(user='my user', passwd='my password')
ftp.cwd('/MY_DIR')
ftp.dir()
I have an error :
ConnectionRefusedError: [Errno 111] Connection refused
The ftp is an EC2 with vsftpd
pasv_enable=YES
pasv_min_port=1024
pasv_max_port=1048
pasv_address=IP
pasv_addr_resolve=YES
Already tried :
The code work on other FTP with and without TLS (hosted on 1and1, OVH...)
I tried this script in NodeJS
const ftpClient = require('ftp-client');
const client = new ftpClient({
host: "IP",
port: 21,
user: "My user", // defaults to "anonymous"
password: "My password" // defaults to "#anonymous"
});
client.connect(() => {
client.download('/MY_DIR/file','/tmp/file', (res) => {
console.log(res)
})
});
Works perfectly fine so I exclude a firewall problem
I have tried enable TLS
ssl_enable=YES
require_ssl_reuse=NO
then
sudo service vsftpd restart
and use
FTP_TLS instead of FTP
but did not work
Also I tried disable passive mode by setting
pasv_enable=NO
then
sudo service vsftpd restart
and ftp.set_pasv(False)
didn't work either
Solution
After using filezilla to debug the method, turn out that our FTP returned 0.0.0.0 despite we defined in /etc/vsftpd.conf
pasv_adress=IP
this post helped us : https://www.centos.org/forums/viewtopic.php?t=52408
You have to comment
listen_ipv6=YES
and enable
listen=YES
in /etc/vsftpd.conf
Also you can override the ftplib's class FTP if you can't access to vsftpd.conf of the FTP
class CustomFTP(ftplib.FTP):
def makepasv(self):
if self.af == socket.AF_INET:
host, port = ftplib.parse227(self.sendcmd('PASV'))
else:
host, port = ftplib.parse229(self.sendcmd('EPSV'), self.sock.getpeername())
if '0.0.0.0' == host:
""" this ip will be unroutable, we copy Filezilla and return the host instead """
host = self.host
return host, port
to force the previous host if '0.0.0.0' is send

boto s3 - How to find url or IP of connection

I want to use this code to connect to S3
conn = S3Connection('<aws access key>', '<aws secret key>')
But I then receive an error: socket.error: [Errno 10053] An established connection was aborted by the software in your host machine
The reason may be that I am behind a proxy server, so I need to know the IP address of the connection in order to open ports.
So the question is, how can I know that IP, or url ( I know that the IP may vary for each connection).
I solved my problem by adding proxy authentication to S3Connection and everything works as expected

Categories

Resources