How to SSH into a Server in Python

09/12/2021

Contents

In this article, you will learn how to SSH into a server in Python.

Using the paramiko module

To SSH into a server in Python, you can use the paramiko module, which provides an implementation of the SSH protocol. Here’s an example of how to use paramiko to SSH into a server:

import paramiko

# create an SSH client object
ssh = paramiko.SSHClient()

# automatically add the server's host key
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

# connect to the server
ssh.connect(hostname='your-server.com', username='your-username', password='your-password')

# execute a command on the server
stdin, stdout, stderr = ssh.exec_command('ls')

# print the output of the command
for line in stdout:
    print(line.strip())

# close the connection
ssh.close()

In this example, you first create an SSHClient object, then set the policy for automatically adding the server’s host key, and finally connect to the server using the connect() method with the appropriate hostname, username, and password. Once connected, you can execute a command on the server using the exec_command() method, which returns standard input, output, and error streams. You can then print the output of the command and close the connection using the close() method. Note that you may need to install the paramiko module using a package manager like pip.