Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python ssh(paramiko) fail to connect to remote machine without password?

Tags:

python

ssh

sftp

I want to connect to my remote machine with python module paramsiko. First, I try with password, it is ok, like this:

import paramiko
import socket
import os

paramiko.util.log_to_file('demo_sftp.log')
username = 'xxxxx'
hostname = 'dev81'
Port = 22
password = "xxxxx"
t = paramiko.Transport((hostname, Port))
t.connect(None, username, password)
sftp = paramiko.SFTPClient.from_transport(t)
# dirlist on remote host
dirlist = sftp.listdir('.')
print("Dirlist: %s" % dirlist)

then I want to remove password, use key, according to demo in demo_sftp like this:

import paramiko
import socket
import os

paramiko.util.log_to_file('demo_sftp.log')
username = 'xxxxx'
hostname = 'dev81'
Port = 22
password = None
host_keys = paramiko.util.load_host_keys(os.path.expanduser('~/.ssh/known_hosts'))
hostkeytype = host_keys[hostname].keys()[0]
hostkey = host_keys[hostname][hostkeytype]
print('Using host key of type %s' % hostkeytype)
t = paramiko.Transport((hostname, Port))
t.connect(hostkey, username, password, gss_host=socket.getfqdn(hostname),
            gss_auth=True, gss_kex=True)
sftp = paramiko.SFTPClient.from_transport(t)
# dirlist on remote host
dirlist = sftp.listdir('.')
print("Dirlist: %s" % dirlist)

This fail with Exception paramiko.ssh_exception.BadAuthenticationType: ('Bad authentication type', [u'publickey', u'password']) (allowed_types=[u'publickey', u'password'])

And I can login with command ssh xxxxx@dev81 without password

like image 553
roger Avatar asked Sep 06 '25 03:09

roger


1 Answers

If you Have passphrase for the Key pair

It throws this error

paramiko.ssh_exception.BadAuthenticationType: ('Bad authentication type', [u'publickey', u'password']) (allowed_types=[u'publickey', u'password'])

To Resolve this

ssh.connect('<your ip>', port=22, username='<username>',password='<passphrase for the RSA key>', key_filename='<full path of the private key>')
like image 87
Javeed Shakeel Avatar answered Sep 07 '25 22:09

Javeed Shakeel