What is the simplest way to SSH using Python?


SSH (secure shell) is helpful for remotely managing computers in a secure manner. To connect to a server, you typically use PuTTy, MobaXTerm, or the command-line ssh application. Every Unix, Linux, and Mac server includes SSH as standard equipment, and it is usable in every data centre. SSH connections have made it feasible for secure remote access to resources, remote command execution, the transmission of software patches and updates, and other administrative or management tasks.

SSH is used in systems administration and file transfer software, as well as to handle routers, server hardware, virtualization platforms, and operating systems (OSes). Additionally, it creates a secure link between nearby and distant computers.

SSH using Paramiko

The easiest way to install paramiko is using pip

python -m pip install paramiko

The output obtained is as follows.

To check if paramiko is install the following command can be used

pip list

Upon checking, the following is obtained.

Install paramiko using .whl file offline.

To do so, we have to download .whl file https://pypi.org/project/paramiko/#files

pip install paramiko-2.7.2-py2.py3-none-any.whl

We can also clone from GitHub and use setup.py to install something directly from the source code.

git clone https://github.com/paramiko/paramiko
cd paramiko
python setup.py install

Using Paramiko

To use paramiko, ensure that you have correctly set up SSH

keys(https://confluence.atlassian.com/bitbucketserver/creating-ssh-keys-776639788.html) on the host machine and when running the python script, these keys are accessible. Once that is done use the following code to connect to a remote server using ssh.

from paramiko import SSHClient
ssh = SSHClient()
ssh.load_system_host_keys()
ssh.connect('user@server:path')
ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command('ls')
print(ssh_stdout) #print the output of ls command

Use the paramiko.client to connect to an SSH server. SSHClient.connect(). The only mandatory parameter is the hostname.

connect(hostname, port=22, username=None, password=None, pkey=None, 
key_filename=None, timeout=None, allow_agent=True, look_for_keys=True, 
compress=False, sock=None, gss_auth=False, gss_kex=False, gss_deleg_creds=True, 
gss_host=None, banner_timeout=None, auth_timeout=None, gss_trust_dns=True, 
passphrase=None, disabled_algorithms=None)

Updated on: 11-May-2023

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements