Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SSH using Python via private keys

In my script, I need to do an SSH to a remote system using a private key and dump the file into its directory.

The command I am using to SSH into the system is this:

ssh -i private_key localhost

Followed by the standard input:

Enter passphrase for key 'private_key'

I am trying to do this in a Python script, but am not sure about the way of writing a command and passing a passphrase as a parameter so that the whole sequence can be automated.

Please suggest me a way to achieve this via a library (Paramiko SSHClient) or a code snippet would be highly really appreciated.

like image 333
AgentLog Avatar asked Dec 06 '25 03:12

AgentLog


1 Answers

SSHClient.connect can handle public key authentication with a simple call:

import paramiko

ssh = paramiko.SSHClient()
ssh.connect(hostname, username=username, key_filename=key_path, password=passphrase)

The password argument is used as a passphrase, when key_filename is provided.


Additionally, you will also have to verify the server's host key (as you must have done with ssh before). See Paramiko "Unknown Server".

like image 152
Martin Prikryl Avatar answered Dec 07 '25 16:12

Martin Prikryl