[Python] How can I run multiple commands on SSH in one go with Paramiko in Python?

Discussão em 'Python' iniciado por Stack, Junho 18, 2025.

  1. Stack

    Stack Membro Participativo

    I've got some code that runs through a list of devices, connects to them via SSH and queries some parameters. The basic code looks like this:

    ssh = paramiko.SSHClient()
    ssh.connect(ip_address, username='root', password=password)

    try:
    ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command('uname -r')
    if ssh_stdout.channel.recv_exit_status() == 0:
    temp = ssh_stdout.readlines()
    if temp:
    kernel_version = temp[0].strip('\n').strip('\"')
    except BaseException as ex:
    print(f'An exception occurred: {ex}')

    try:
    ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command('lsb_release -rs')
    if ssh_stdout.channel.recv_exit_status() == 0:
    temp = ssh_stdout.readlines()
    if temp:
    ubuntu_version = temp[0].strip('\n').strip('\"')
    except BaseException as ex:
    print(f'An exception occurred: {ex}')


    But there are a lot of devices and it takes a long time to run. It's faster to run multiple commands in one go:

    try:
    ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command('uname -r; lsb_release -rs')
    if ssh_stdout.channel.recv_exit_status() == 0:
    temp = ssh_stdout.readlines()
    if temp[0]:
    kernel_version = temp[0].strip('\n').strip('\"')
    if temp[1]:
    ubuntu_version = temp[1].strip('\n').strip('\"')
    except BaseException as ex:
    print(f'An exception occurred: {ex}')


    but how can I handle one command passing and one failing? Is there a better way of doing this?

    Continue reading...

Compartilhe esta Página