pysftp AuthenticationException while connecting to server with private key - python

I am trying to connect to SFTP server. I have a private key along with a password.
I have tried to read related questions on SO, but have been unable to successfully connect.
This is what I have tried:
pysftp.Connection(host=<hostname>, username=<username>,
password=<password>, private_key=<path to .ppk file>)
AuthenticationException: Authentication failed
pysftp.Connection(host=<hostname>, username=<username>,
private_key_pass=<password>, private_key=<path to .ppk file>)
SSHException: not a valid DSA private key file
However, I can use the same credentials and connect with FileZilla. FileZilla asked for password and converted the .ppk file into an unprotected file.
I tried to use the same host name, username and key file as used in FileZilla, but I continue getting errors.
Also tried connecting using Paramiko.

I could finally connect.
Converted the file to a .pem file using PuTTY. Passed this .pem file and kept the rest of the parameters the same as before.
pysftp.Connection(host='hostname', username='username',
password='password', private_key='path to .pem file')
Hope this helps someone having similar issues.

I solved this problem by downgrading from pysftp0.2.9 to pysftp 0.2.8
pip install pysftp==0.2.8
I used private key with private key password in the connection string like this:
import pysftp as sftp
import sys
srver = sftp.Connection(host='xx.xxx.xx.xx',username='xxxxx',password='xxx',port=9999,private_key='C:\\Users\xxxx\xxx\id_rsa.ppk',private_key_pass='xxxxxx')
Remember that port is actually a number not a string. This solution will work for all those who want to connect using private key and private key password with host name, username and user password.

I had the same problem on a Linux environment and I was trying to follow the solution from the accepted answer. The first problem I had was converting the .ppk file to a .pem file. I find on a Debian environment, we can convert the .ppk file to a .pem file using PuTTY tools
$ sudo apt-get install putty-tools
$ puttygen abc.ppk -O private-openssh -o abc.pem
The second problem I had with trying out the accepted answer was an Authentication Error, I used private_key_pass instead of password and I was able to make the connection.
cnopts = pysftp.CnOpts()
cnopts = modify_cnopts_as_you_wish(cnopts)
srv = pysftp.Connection(host="hostname", username="user",
private_key='path_to_abc.pem',
private_key_pass="password",
cnopts=cnopts)

You could directly use the option -m PEM when you add the key with ssh-keygen from your linux console instead of using Putty.
ssh-keygen -t rsa -m PEM

I was able to solve same issue with
ssh-keygen -t rsa -m PEM" command and
pysftp.Connection(host='hostname', username='username',
private_key_pass='password', private_key='path to .pem file')

Related

fatal: protocol error: bad line length character: Pa

I have recently been working with Git in PyCharm.
But when I test the Git URL, it gives me this error:
fatal: protocol error: bad line length character: Pa
The remote repository in on an internal server access through a dedicated account:
anAccount#ourServer:ourRepo
Check first if switching protocol helps:
if the Git URL is https://github.com/..., switch to ssh://git#github.com/...
if the Git URL is git#github.com:..., switch to https://github.com/...
For an SSH URL, try at least to:
generate, for testing, a PEM ssh key, without passphrase
register the public key in yourUser#yourRemoteServer:~/.ssh/authorized_keys (make sure to copy the public key content id_rsa.pub as one line in that authorized_keys files)
make sure to use OpenSSH, not Plink.exe
That is:
set PATH=C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\
set GH=C:\path\to\git
set PATH=%GH%\bin;%GH%\usr\bin;%GH%\cmd;%GH%\mingw64\bin;%PATH%
ssh-keygen -m PEM -t rsa -P ""
# Copy the %USERPROFILE%\.ssh\id_rsa.pub content to the remote server

Ansible with Github: Permission denied (Publickey)

I'm trying to understand the GitHub ssh configuration with Ansible (I'm working on the Ansible: Up & Running book). I'm running into two issues.
Permission denied (publickey) -
When I first ran the ansible-playbook mezzanine.yml playbook, I got a permission denied:
failed: [web] => {"cmd": "/usr/bin/git ls-remote '' -h refs/heads/HEAD", "failed": true, "rc": 128}
stderr: Permission denied (publickey).
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
msg: Permission denied (publickey).
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
FATAL: all hosts have already failed -- aborting
Ok, fair enough, I see several people have had this problem. So I jumped to appendix A on running Git with SSH and it said to run the ssh-agent and add the id_rsa public key:
eval `ssh-agent -s`
ssh-add ~/.ssh/id_rsa
Output: Identity AddedI ran ssh-agent -l to check and got the long string: 2048 e3:fb:... But I got the same output. So I checked the Github docs on ssh key generations and troubleshooting which recommended updating the ssh config file on my host machine:
Host github.com
User git
Port 22
Hostname github.com
IdentityFile ~/.ssh/id_rsa
TCPKeepAlive yes
IdentitiesOnly yes
But this still provides the same error. So at this point, I start thinking it's my rsa file, which leads me to my second problem.
Key Generation Issues - I tried to generate an additional cert to use, because the Github test threw another "Permission denied (publickey)" error.
Warning: Permanently added the RSA host key for IP address '192.30.252.131' to the list of known hosts.
Permission denied (publickey).
I followed the Github instructions from scratch and generated a new key with a different name.
ssh-keygen -t rsa -b 4096 -C "me#example.com"
I didn't enter a passphrase and saved it to the .ssh folder with the name git_rsa.pub. I ran the same test and got the following:
$ ssh -i ~/.ssh/git_rsa.pub -T git#github.com
###########################################################
# WARNING: UNPROTECTED PRIVATE KEY FILE! #
###########################################################
Permissions 0644 for '/Users/antonioalaniz1/.ssh/git_rsa.pub' are too open.
It is required that your private key files are NOT accessible by others.
This private key will be ignored.
bad permissions: ignore key: ~/.ssh/github_rsa.pub
Permission denied (publickey).
I checked on the permissions and did a chmod 700 on the file and I still get Permission denied (publickey). I even attempted to enter the key into my Github account, but first got a message that the key file needs to start with ssh-rsa. So I started researching and hacking. Started with just entering the long string in the file (it started with --BEGIN PRIVATE KEY--, but I omitted that part after it failed); however, Github's not accepting it, saying it's invalid.
This is my Ansible command in the YAML file:
- name: check out the repository on the host
git: repo={{ repo_url }} dest={{ proj_path }} accept_hostkey=yes
vars:
repo_url: git#github.com:lorin/mezzanine-example.git
This is my ansible.cfg file with ForwardAgent configured:
[defaults]
hostfile = hosts
remote_user = vagrant
private_key_file = .vagrant/machines/default/virtualbox/private_key
host_key_checking = False
[ssh_connection]
ssh_args = -o ControlMaster=auto -o ControlPersist=60s -o ForwardAgent=yes
The box is an Ubuntu Trusty64 using Mac OS. If anyone could clue me into the file permissions and/or Github key generation, I would appreciate it.
I suspect the key permissions issue is because you are passing the public key instead of the private key as the arugment to "ssh -i". Try this instead:
ssh -i ~/.ssh/git_rsa -T git#github.com
(Note that it's git_rsa and not git_rsa.pub).
If that works, then make sure it's in your ssh-agent. To add:
ssh-add ~/.ssh/git_rsa
To verify:
ssh-add -l
Then check that Ansible respects agent forwarding by doing:
ansible web -a "ssh-add -l"
Finally, check that you can reach GitHub via ssh by doing:
ansible web -a "ssh -T git#github.com"
You should see something like:
web | FAILED | rc=1 >>
Hi lorin! You've successfully authenticated, but GitHub does not provide shell access.
I had the same problem, it took me some time, but I have found the solution.
The problem is the URL is incorrect.
Just try to change it to:
repo_url: git://github.com/lorin/mezzanine-example.git
I ran into this issue and discovered it by turning verbosity up on the ansible commands (very very useful for debugging).
Unfortunately, ssh often throws error messages that don't quite lead you in the right direction (aka permission denied is very generic...though to be fair that is often thrown when there is a file permission issue so perhaps not quite so generic). Anyways, running the ansible test command with verbose on helps recreate the issue as well as verify when it is solved.
ansible -vvv all -a "ssh -T git#github.com"
Again, the setup I use (and a typical one) is to load your ssh key into the agent on the control machine and enable forwarding.
steps are found here Github's helpful ssh docs
it also stuck out to me that when I ssh'd to the box itself via the vagrant command and ran the test, it succeeded. So I had narrowed it down to how ansible was forwarding the connection. For me what eventually worked was setting
[paramiko_connection]
record_host_keys = False
In addition to the other config that controls host keys verification
host_key_checking = False
which essentially adds
-o StrictHostKeyChecking=no
to the ssh args for you, and
-o UserKnownHostsFile=/dev/null
was added to the ssh args as well
found here:
Ansible issue 9442
Again, this was on vagrant VMs, more careful consideration around host key verification should be taken on actual servers.
Hope this helps

How to do multihop ssh with fabric

I have a nat and it has various server
So from my local server I want to go to nat and then from nat i have to ssh to other machines
Local-->NAT(abcuser#publicIP with key 1)-->server1(xyzuser#localIP with key 2)
nat has different ssh key
and each of the server has different ssh key
how can i accomplish this type of multihop ssh using fabric
I tried using env.roledefs feature but it doesnt seems to be working
also I am not sure how to define two ssh keys.I know we can define a list of keys with env.key_filename but issue is will it check each key with each server?How can I be more specific and match a key with one server only
I have tried using command from my local machine
fab deploy -g 'ec2-user#54.251.151.39' -i '/home/aman/Downloads/aws_oms.pem'
and my script is
from __future__ import with_statement
from fabric.api import local, run, cd, env, execute
env.hosts=['ubuntu#10.0.0.77']
env.key_filename=['/home/ec2-user/varnish_cache.pem']
def deploy():
run("uname -a")
It's possible. Double hop to 10.0.0.2 (and list files) via gateway hop 10.0.0.1. Basically, you simply nest the connections with the gateway parameter.
# coding: utf-8
from fabric import Connection
path = '/'
conn1 = Connection(host='user1#10.0.0.1', connect_kwargs={'password': '***'})
conn2 = Connection(host='user2#10.0.0.2', connect_kwargs={'password': '***'}, gateway=conn1)
result = conn2.run(f'''cd {path} && ls -al''', hide=True)
conn2.close()
conn1.close()
msg = "Ran {0.command!r} on {0.connection.host}, got stdout:\n{0.stdout}"
print(msg.format(result))
Please remember to run the SSH connection manually once to introduce the servers to each other!
Install via
pip3 install --upgrade fabric
pip3 install cryptography==2.4.2 # optional to hide some annoying warnings
http://docs.fabfile.org/en/latest/concepts/networking.html
Python 3.6+.
In order to connect to remote hosts via an intermediate server, you can use the --gateway command-line option :
http://docs.fabfile.org/en/latest/usage/fab.html#cmdoption-g
Or, alternatively, set the env.gateway variable inside your fabfile :
http://docs.fabfile.org/en/latest/usage/env.html#gateway
For more detail information, see:
http://docs.fabfile.org/en/stable/concepts/networking.html#ssh-gateways

I can manully ssh2 to remote host, but paramiko can not, why?

I want use paramiko to ssh2 to a remote host by public-key authentication, I setup the keys like these steps:
On local:
Local> ssh-keygen
Generating 1024-bit dsa key pair
9 o.oOo..oOo.o
Key generated.
Passphrase :
Again :
Private key saved to /home/local/.ssh2/id_dsa_1024_a
Public key saved to /home/local/.ssh2/id_dsa_1024_a.pub
Local> cd ~/.ssh2
Local> echo "IdKey id_dsa_1024_a" > identification
Local> scp id_dsa_1024.pub remote#remote-host:~/.ssh2/local.pub
On remote:
Remote> ssh-keygen
...omit...
Remote> cd ~/.ssh2
Remote> echo "Key local.pub" > authorization
After things above, I can just use ssh remote#remote-host to login.
However,I failed to use python's paramiko module to login remote-host:
conn = paramiko.SSHClient()
conn.set_missing_host_key_policy(paramiko.AutoAddPolicy())
conn.connect(remote-host, 22, username=remote,password='')
Alway error: Authentication failed.
I'm so confused. :(
Have you tried setting the key_filename option when connecting? I'm not sure that paramiko will automatically look at your private key in ~/.ssh like the SSH CLI client does.
paramiko documentation
import os
import paramiko
ssh = paramiko.SSHClient()
ssh.load_host_keys(os.path.abspath('.ssh/known_hosts'))
ssh.connect(some_host_in_known_hosts)
this fixed the same issue for me quite well this morning using python 2.7

Connecting to EC2 using keypair (.pem file) via Fabric

Anyone has any Fabric recipe that shows how to connect to EC2 using the pem file?
I tried writing it with this manner:
Python Fabric run command returns "binascii.Error: Incorrect padding"
But I'm faced with some encoding issue, when I execute the run() function.
To use the pem file I generally add the pem to the ssh agent, then simply refer to the username and host:
ssh-add ~/.ssh/ec2key.pem
fab -H ubuntu#ec2-host deploy
or specify the env information (without the key) like the example you linked to:
env.user = 'ubuntu'
env.hosts = [
'ec2-host'
]
and run as normal:
fab deploy
Without addressing your encoding issue, you might put your EC2 stuff into an ssh config file:
~/.ssh/config
or, if global:
/etc/ssh_config
There you can specify your host, ip address, user, identify file, etc., so it's a simple matter of:
ssh myhost
Example:
Host myhost
User ubuntu
HostName 174.129.254.215
IdentityFile ~/.ssh/mykey.pem
For more details: man ssh_config
Another thing you can do is set the key_filename in the env variable: https://stackoverflow.com/a/5327496/1729558

Categories

Resources