Python: Make SFTP connection using proxyhost and proxyport - python

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.

Related

Oops, unhandled type 3 ('unimplemented') error while connecting SFTP with Databricks

I'm trying to connect to SFTP from a notebook with databricks in python. My notebook looks like this:
import pysftp
import paramiko
# set parameters
host_name = 'xx.xxx.xxx.xxx'
username = 'FTP_USERNAME'
file_path_to_rsa_key = "/path/key_rsa"
cnopts = pysftp.CnOpts()
cnopts.hostkeys = None
# connect to SFTP
sftp = pysftp.Connection(host_name, username=username, private_key=file_path_to_rsa_key, cnopts=cnopts)
data = sftp.listdir()
sftp.close()
# Prints out the directories and files, line by line
for i in data:
print(i)
I have the following error:
Oops, unhandled type 3 ('unimplemented')
when running the following block:
try:
conn = pysftp.Connection(host_name, username=username, private_key=file_path_to_rsa_key, cnopts=cnopts)
print("connection established successfully")
except:
print('failed to establish connection to targeted server')
It print connection established successfully
What does it mean? What should I do? Is the issue with listdir()?
It seems that the issue is mostly because pysftp. I end up switching entirely to paramiko and everything is working fine. The SFTP server modified the login response and pysftp was too strict in the acceptable responses to take it without trouble. I noticed something similar when I tried to use a non-RSA private key that worked fine for ssh / sftp directly but not pysftp.
There is also some interesting information here pysftp vs. Paramiko

How to connect to Droxbox via sftp Python?

I want to send/download file from Droxbox via Python. I've tried pysftp and paramiko, but the connect() call will hang. Below is my code.
import paramiko
# create a client
ssh = paramiko.SSHClient()
# can alos choose .WarningPolicy(), .RejectPolicy()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname="dropbox.com", username="my username", password="my pw")
# The call will hang there
sftp code
import pysftp as sftp
cnopts = sftp.CnOpts()
cnopts.hostkeys = None
'''If I don't set up cnopts, I'll get error - No hostkey for host dropbox.com found.
But I got a warning if I set up the above cnopts -
CryptographyDeprecationWarning: Support for unsafe construction of
public numbers from encoded data will be removed in a future
version. Please use EllipticCurvePublicKey.from_encoded_point
self.ecdsa_curve.curve_class(), pointinfo
'''
s = sftp.Connection(host="dropbox.com",
username="xi#transcriptic.com",
password="Python#2018",
cnopts=cnopts)
Any suggestions would be greatly appreciated!
I don't believe that Dropbox supports SFTP, sadly.

Paramiko does not connect

I try to upload a file to a server via sftp using paramiko.
def send_file(server_, port_, user_, passwd_, file_, dir_):
"""
:return:
"""
try:
transport = paramiko.Transport((server_, int(port_)))
transport.connect(username=user_, password=passwd_)
sftp = paramiko.SFTPClient.from_transport(transport)
sftp.put(file_, dir_)
sftp.close()
except RuntimeError, err:
print(str(err))
If I execute this function it just hangs (no response, no error messages), until the socket times out.
The credentials are correct, I tried them with sftp and ssh clients from the same machine and the same network.
I also passed the Transport and connect values directly, no change.
The logs on the server_ don't show any connections when I use this function.
The host key is in my known_hosts file.
The first statement in the try-block succeeds (I passed a string instead of an int to port_, this throws an exception), the second line seems to have problems.
What's the problem here?
Thanks in advance!
UPDATE 1:
I tried this in ipython2 and it works. The function above is in a PyQt program and executed via
self.connect(self.b_upload, QtCore.SIGNAL("clicked()"), self.onUpload)
Function onUpload:
def onUpload(self):
file_, ok = QtGui.QInputDialog.getText(self, 'Input Dialog', 'Datei inklusive Pfad angeben: ')
server_, port_, user_, passwd_, dir_ = ftpmod.read_config()
ftpmod.send_file(server_, port_, user_, passwd_, file_, dir_)
You can send via sftp, using ssh.open_sftp:
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(
paramiko.AutoAddPolicy())
ssh.connect(host, username, password)
ftp = ssh.open_sftp()
ftp.put(localpath, remotepath)
ftp.close()

How to connect to SFTP through Paramiko with SSH key - Pageant

I am trying to connect to an SFTP through Paramiko with a passphrase protected SSH key. I have loaded the key into Pageant (which I understand is supported by Paramiko) but I can't get it to decrypt my private key.
I have found this example here that references allow_agent=True but this does not appear to be a parameter that can be used with the SFTPClient.
Can anyone advise if it is possible to work with Paramiko and Pageant in this way?
This is my code at the moment - which raises PasswordRequiredException
privatekeyfile = 'path to key'
mykey = paramiko.RSAKey.from_private_key_file(privatekeyfile)
transport = paramiko.Transport(('host', 'port'))
transport.connect('username',pkey = mykey)
sftp = paramiko.SFTPClient.from_transport(transport)
You have to provide a passphrase, when loading an encrypted key using the RSAKey.from_private_key_file.
Though note that you do not have to load the key at all, when using the Pageant. That's the point of using an authentication agent. But only the SSHClient class supports the Pageant. The Transport class does not, on its own.
You can follow the code in How to use Pageant with Paramiko on Windows?
Though as the allow_agent is True by default, there is actually nothing special about the code.
Once connected and authenticated, use the SSHClient.open_sftp method to get your instance of the SFTPClient.
ssh = paramiko.SSHClient()
ssh.connect(host, username='user', allow_agent=True)
sftp = ssh.open_sftp()
You will also need to verify the host key:
Paramiko "Unknown Server"
This worked for me
privatekeyfile = 'path to key'
mykey = paramiko.RSAKey.from_private_key_file(privatekeyfile)
ssh_client = paramiko.SSHClient()
ssh_client.load_system_host_keys()
ssh_client.connect(hostname='host', username='user', allow_agent=True, pkey=mykey)
ftp_client = ssh_client.open_sftp()
print(ftp_client.listdir('/'))

Port forwarding with Paramiko

I'm trying to do some port forwarding from a python app using Paramiko. I can set up the SSH connection just fine, but I'm a bit stumped as to how to use paramiko.Transport. I've already found this file, but I can't work out what's going on in it. From looking at the paramiko.Transport docs, it seems that a single line using the open_channel function, but I can't work out how to implement that. I'm trying to replicate a simple ssh -L 8000:localhost:8000.
Can anyone help me out?
Please find some code using paramiko-1.7.7.1, pycrypto-2.6 and the forward.py script from which I did remove code from the line 115 to the end (to avoid options parsing).
import paramiko, sys
from forward import forward_tunnel
remote_host = "target_host"
remote_port = 8000
local_port = 8000
ssh_host = "my_ssh_host"
ssh_port = 22
user = "login"
password = "s3cr3t"
transport = paramiko.Transport((ssh_host, ssh_port))
# Command for paramiko-1.7.7.1
transport.connect(hostkey = None,
username = user,
password = password,
pkey = None)
try:
forward_tunnel(local_port, remote_host, remote_port, transport)
except KeyboardInterrupt:
print 'Port forwarding stopped.'
sys.exit(0)
I've tested it successfully from a Windows station, using a ssh server under Red Hat and pointing to a 3rd server. (I'm using Python 2.7.2)
Hope it helps,
You can use https://github.com/pahaz/sshtunnel
pip install sshtunnel
Code example:
import sshtunnel
with sshtunnel.open(
(ssh_host, ssh_port),
ssh_host_key=None,
ssh_username=ssh_user,
ssh_password=ssh_password,
ssh_private_key=None,
remote_bind_address=(REMOTE_HOST, REMOTE_PORT)) as server:
def do_something(port):
# Do something with port
pass
print("LOCAL PORT:", server.local_bind_port)
do_something(server.local_bind_port)

Categories

Resources