Paramiko does not connect - python

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()

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

Fetch prelogin banner from SSH server using Paramiko without authenticating

I am trying to fetch banner from sever using below code. But the result always says "None", even thought banner exists. I have tried with Python 2 and 3, Paramiko 2.4 and 2.7.0, same result as "None".
Can anyone correct/help me?
The code is based on:
Is there a way using paramiko and python to get the banner of the ssh server you connected to?
The banner is configured in sshd_config using Banner directive.
# !/usr/bin/python
import paramiko
def grab_banner(ip_address, port):
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
client.connect(ip_address, port=port, username='username',
password='bad-password-on-purpose')
except:
return client._transport.get_banner()
if __name__ == '__main__':
print grab_banner('192.168.1.26', 22)
Thanks
In general I believe that your code should work. But as after failed password authentication, Paramiko tries in vain various other authentication methods, the further attempts will discard the banner (it looks like a bug in Paramiko to me).
Prevent that by setting look_for_keys and allow_agent in SSHClient.connect:
try:
client.connect(ip_address, port=port, username='username',
password='bad-password-on-purpose',
look_for_keys=False, allow_agent=False)
except:
return client._transport.get_banner()
Here is a fix for Paramiko that allows retrieving the banner without the above workaround:
https://github.com/paramiko/paramiko/pull/438

Cannot close Paramiko connection

I am trying to execute some command on remote server using Paramiko and re-purposed some code from net. From Paramiko documents, it say that you have to close the connection. But I am getting errors while doing that.
class ssh:
paramiko.util.log_to_file("filename_new.log")
client = None
def __init__(self, address, username, password):
self.client=paramiko.SSHClient()
self.client.set_missing_host_key_policy(paramiko.client.AutoAddPolicy())
self.client.connect(hostname=address, username=username, password=password)
def sendCommand(self, command):
if(self.client):
couldNotConnect = False
stdin, stdout, stderr = self.client.exec_command(command, get_pty=True)
stdout = stdout.readlines()
self.client.close()
else:
stdout = "Could Not Connect"
couldNotConnect = True
return stdout
connection = ssh(serverName, userName, passWord)
dfDetails = connection.sendCommand("df -hT")
upTime = connection.sendCommand("uptime")
I am getting the below error:
File "/home/amarc/development/djago/venv/lib/python3.6/site-packages/paramiko/client.py", line 508, in exec_command
chan = self._transport.open_session(timeout=timeout)
AttributeError: 'NoneType' object has no attribute 'open_session'
But when I remove the self.client.close(), it works fine. But I am worried if not closing the connection might cause problem if the program was run multiple times.
And is using __init__ the right way to create a connection since I might be supplying the function with different credentials every time.
I'd recommend you to go for either Fabric (http://www.fabfile.org/) or Ansible and not rely purely on Paramiko since you'll have to reimplement a lot of details. Those tools are already using it but behind the scenes.
The SSHClient.close call has to match with SSHClient.connect.
You call SSHClient.connect once, but SSHClient.close for every command.
Call SSHClient.close only once, after you execute all commands.

Python: Make SFTP connection using proxyhost and proxyport

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.

Is there a way using Paramiko and Python to get the banner of the SSH server you connected to?

Is there a way using Paramiko and Python to get the banner of the SSH server you attempt to connect to?
I am dealing with an ultra secure server setup process for many machines and the passwords are generated via a predefined cipher key which get's printed out at with the SSH banner. I have access to the utility that will give me the password, but I need the text in the banner to actually generate the initial password.
Looks like this wasn't a feature. Good thing I requested it and the totally awesome developers put it in...
https://github.com/paramiko/paramiko/issues/273
# !/usr/bin/python
import paramiko
def grab_banner(ip_address, port):
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
client.connect(ip_address, port=port, username='username', password='bad-password-on-purpose')
except:
return client._transport.get_banner()
if __name__ == '__main__':
print grab_banner('192.168.1.26', 22)

Categories

Resources