SoFunction
Updated on 2024-11-18

How to connect to an SSH server and execute commands using Python

actual development, sometimes often need to view the log, sometimes use ssh tools to open in order to see the error log and more trouble, so today to bring a simple python based on the small tools.

First you need to install the library paramiko

Direct installation using the command

pip install paramiko

The paramiko library is an open source, SSH2 protocol-based library that enables SSH connections and the transfer of data.

paramiko is a pure Python implementation of the SSH2 client , support for authentication , SFTP client , and remote execution of commands , etc. paramiko library provides a wealth of classes and methods , to help users quickly implement SSH communication features .

In practice, the paramiko library is often used in scenarios such as building automated operations systems, remote deployments, and multi-computer collaborations.

Define the MySshClient class

class MySshClient:
    def __init__(self, ssh_client):
        self.ssh_client = ssh_client
    def exec_command(self, cmd):
        try:
            stdin, stdout, stderr = self.ssh_client.exec_command(cmd)
            return stdin, stdout, stderr
        except Exception as e:
            print(f"Error executing command {cmd}: {e}")
    def __enter__(self):
        return self
    def __exit__(self, exc_type, exc_val, exc_tb):
        self.ssh_client.close()
In this code,We define a MySshClient resemble,connectivity SSH server and execute the command。您可以使用该resemble创建一个实例,adapted and approved by connect() method connects to the SSH server (computer)。
def connect(host, port, username, password):
    ssh = ()
    ssh.set_missing_host_key_policy(())
    try:
        ssh.load_system_host_keys()
        (host, port, username, password,timeout=3)
    except :
        raise Exception(f"main unit {host}connection failure,Please check your parameters")
    except  as e:
        raise Exception(f"exist {host}Something is wrong with the connection.: {e}")
    except  as e:
        raise Exception(f" {host} Unable to pass verification: {e}")
    except Exception as e:
        raise Exception(f" connect to{host}:{port}: {e}overtime pay")
    return ssh

This is to add exception handling to the function, to facilitate the debugging of the code

execute a command

After connecting to an SSH server, you can use the exec_command() method to execute commands. This method returns a tuple containing the server's output, errors, and input. You can provide this tuple to the with keyword for processing as needed.

2. Connect to the host

Before connecting to the SSH server, you need to specify the hostname, port, username and password. Example:

host = input("Host: Please enter a host name.")
port = int(input("Port: 22 by default")or 22) 
username = input("Username: Please enter a username.")
password = ("Password: Please enter a password.")

port = int(input("Port: 22 by default") or 22) What this code means is

Default port 22, if your ssh port is not 22, you can change it.

For the password, if you don't want others to see it, use the getpass function to encrypt it.

Creating and connecting to a MySshClient instance

ssh = connect(host, port, username, password)

After a successful connection, execute the command and process the output

After a successful connection, you can use the exec_command() method to execute commands and use the with keyword to process the server's output:

with MySshClient(ssh) as client:
    stdin, stdout, stderr = client.exec_command("ls -l")
    with stdout:
        print(().decode())
    with stderr:
        print(().decode())

This will execute the "ls -l" command after connecting to the SSH server and output the results. Note that this example only displays the output, if there are errors, the error message will be displayed on the console.

The complete code is as follows.

import paramiko
import os
import getpass
class MySshClient:
    def __init__(self, ssh_client):
        self.ssh_client = ssh_client
    def exec_command(self, cmd):
        try:
            stdin, stdout, stderr = self.ssh_client.exec_command(cmd)
            return stdin, stdout, stderr
        except Exception as e:
            print(f"Error executing command {cmd}: {e}")
    def __enter__(self):
        return self
    def __exit__(self, exc_type, exc_val, exc_tb):
        self.ssh_client.close()
def connect(host, port, username, password):
    ssh = ()
    ssh.set_missing_host_key_policy(())
    try:
        ssh.load_system_host_keys()
        (host, port, username, password,timeout=3)
    except :
        raise Exception(f"main unit {host}connection failure,Please check your parameters")
    except  as e:
        raise Exception(f"Error connecting to {host}: {e}")
    except  as e:
        raise Exception(f"Host key for {host} could not be verified: {e}")
    except Exception as e:
        raise Exception(f" connect to{host}:{port}: {e}overtime pay")
    return ssh
if __name__ == '__main__':  
    host = input("Host: Please enter a host name.")
    port = int(input("Port: 22 by default")or 22)
    username = input("Username: Please enter a username.")  
    password = ("Password: Please enter a password.")
    print('Connected in ...........')
    ssh = connect(host, port, username, password,)
    with MySshClient(ssh) as client:
        stdin, stdout, stderr = client.exec_command("ls -l")
        with stdout:
            print(().decode())
        with stderr:
            print(().decode())

Of course you can also use sftp for the transfer

# Upload
current_path = ()   # Get current path
print(current_path)
filename = '\\'     		# File name
file = current_path + f'{filename}'			# Path to the current file
sftp = client.open_sftp() 						# Connect using sftp
(file, '/root/')			# Upload files
('/root/', current_path+'/')     #Download file

to this article on the use of Python to connect to SSH servers and execute commands to this article, more related to Python to connect to SSH server content please search for my previous articles or continue to browse the following related articles I hope that you will support me in the future more!