Paramiko - Использование переменных в exec_command - PullRequest
0 голосов
/ 15 октября 2019

Встраивание небольшого скрипта "ssh в устройство и запуск пары команд", и я не могу заставить его работать. Большая цель состоит в том, чтобы иметь что-то, что ssh на отдельных хостах, а затем пингует список адресов и возвращает ip1 - ОК;ip2 - ОК, список результатов. Еще не зашел так далеко.

Я пытаюсь выполнить команду: ping -c 5 <IP Addresses>, так как конечная цель - запустить цикл, проходящий по списку IP-адресов для проверки связи с этого хоста.

Ожидаемый результат будет:

Trying to connect to 192.168.1.1 (1/5)
Connected to 192.168.1.1
PING 192.168.1.1 (192.168.1.1): 56 data bytes
64 bytes from 192.168.1.1: icmp_seq=0 ttl=64 time=1.411 ms
64 bytes from 192.168.1.1: icmp_seq=1 ttl=64 time=0.168 ms
64 bytes from 192.168.1.1: icmp_seq=2 ttl=64 time=0.136 ms
64 bytes from 192.168.1.1: icmp_seq=3 ttl=64 time=0.524 ms
Command done, closing SSH connection

Trying to connect to 192.168.1.1 (1/5)
Connected to 192.168.1.1
PING 192.168.1.1 (192.168.1.1): 56 data bytes
64 bytes from 192.168.1.2: icmp_seq=0 ttl=64 time=1.411 ms
64 bytes from 192.168.1.2: icmp_seq=1 ttl=64 time=0.168 ms
64 bytes from 192.168.1.2: icmp_seq=2 ttl=64 time=0.136 ms
64 bytes from 192.168.1.2: icmp_seq=3 ttl=64 time=0.524 ms
Command done, closing SSH connection

Я пробовал:

ssh.exec_command('ping -c 5', ipaddrss)
ssh.exec_command('ping -c 5' + ipaddrss)

Вот то, что у меня сейчас (полный сценарий):

    import sys
    import time
    import select
    import paramiko

    host='192.168.1.1'
    port=22
    username = 'root'
    password = 'Password1'
    i = 1
    ipaddrss = '192.168.1.1'
    # Try to connect to the host. Retry a few times if it fails.
    while True:
        print "Trying to connect to %s (%i/5)" % (host, i)
        try:
            ssh = paramiko.SSHClient()
            ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            ssh.connect(host, port , username, password)
            print "Connected to %s" % host
            break
        except paramiko.AuthenticationException:
            print "Authentication failed when connecting to %s" % host
            sys.exit(1)
        except:
            print "Could not SSH to %s, waiting for it to start" % host
            i += 1
            time.sleep(2)

        # If we could not connect within time limit
        if i == 5:
            print "Could not connect to %s. Giving up" % host
            sys.exit(1)

    # Executing the command
    cmd = 'ping -c 5'
    stdin, stdout, stderr = ssh.exec_command(cmd, ipaddrss)

    # Wait for the command to terminate
    while not stdout.channel.exit_status_ready():
        # Only print data if there is data to read in the channel
        if stdout.channel.recv_ready():
            rl, wl, xl = select.select([stdout.channel], [], [], 0.0)
            if len(rl) > 0:
                # Print data from stdout
                print stdout.channel.recv(1024),

    # Disconnect from the host
    print "Command done, closing SSH connection"
    ssh.close()

Любая помощь или рекомендации приветствуются!

Спасибо!

=================

Решено:

Добавлен пробел после "5":

# Executing the command
cmd = 'ping -c 5 ' + ipaddrss
stdin, stdout, stderr = ssh.exec_command(cmd)

Работает сейчас. Спасибо!

========
Комментарий:

Не верьте, что это полностью совпадает: Передайте переменную Python внутри команды с помощью Paramiko

...