0

I am trying to ssh into a linux VM using the paramiko module. The expectation from my task is to ping a set of IPs from this VM (linux master VM) to multiple remote IP something like 10.151.0.31 , 10.152.0.31,10.153.0.31,10.154.0.31 and so on.

It is given that the mentioned IPs above are reachable through linux master VM. The ping works fine when done manually from the VM.

Below is the code that I looked up from the examples and tried to find solution ssh_test_vm.py

import paramiko
import subprocess

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname='192.168.202.46', username='root', password='password')
host = '10.151.0.31'
command = ['ping','-c1','-w20',host]
stdin, stdout, stderr = ssh.exec_command(subprocess.call(command))

for line in stdout.read().splitlines():
    print(line)

ssh.close()


Output to above looks like below:

[root@pf2-jenkins-agent-vm Automation]# python3 ssh_test_vm.py
PING 10.151.0.31 (10.151.0.31) 56(84) bytes of data.

--- 10.151.0.31 ping statistics ---
20 packets transmitted, 0 received, 100% packet loss, time 500ms

Traceback (most recent call last):
  File "ssh_test_vm.py", line 9, in <module>
    stdin, stdout, stderr = ssh.exec_command(subprocess.call(command))
  File "/usr/local/lib/python3.6/site-packages/paramiko/client.py", line 514, in exec_command
    chan.exec_command(command)
  File "/usr/local/lib/python3.6/site-packages/paramiko/channel.py", line 72, in _check
    return func(self, *args, **kwds)
  File "/usr/local/lib/python3.6/site-packages/paramiko/channel.py", line 254, in exec_command
    m.add_string(command)
  File "/usr/local/lib/python3.6/site-packages/paramiko/message.py", line 274, in add_string
    self.add_int(len(s))
TypeError: object of type 'int' has no len()

Although I just tried pinging one of the IP and not the full list of IP, also I am not sure if this is the way it's done. The ping output needs to be saved and monitored for packet loss later.

  • 1
    Don't you want this? `stdin, stdout, stderr = ssh.exec_command('ping -c1 -w20 ' + host)`? – Martin Prikryl Jul 15 '20 at 06:27
  • @MartinPrikryl thanks for the suggestion. This worked for me,didn't realise that I could do this without having to use subprocess module. ```python hosts = ['10.151.0.31','10.152.0.31','10.153.0.31','10.154.0.31'] for host in hosts: stdin, stdout, stderr = ssh.exec_command('ping -c1 -w20 '+host) for line in stdout.read().splitlines(): print(line) ``` – turmoilawaits Jul 15 '20 at 08:25
  • `stdout.read().splitlines()` => `stdout.readlines()` – Martin Prikryl Jul 15 '20 at 08:33

0 Answers0