I have setup nested loops - that reads a file for IP-Addresses and a file for commands (individually they work but as soon as i merged the two iterations SSH is not done on all the devices in the list. I did add some increments to see if code iterates properly..
Code:
#!/usr/bin/python
import paramiko
import sys
import time
import select
import re
import os
ip_add_file = open(r'ip-list','r')
cmd = open(r'cmd','r')
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
i=0
try:
for host in ip_add_file:
strip_host = host.strip()
print strip_host + " START OF DEVICE"
#i = i + 1
#print i
#ssh.connect(hostname=strip_host, username='test', password='test')
#for cmds in cmd:
ssh.connect(hostname=strip_host, username='test', password='test')
i = i + 1
print i
# strip_cmd=cmds.strip()
# print strip_cmd
for cmds in cmd:
strip_cmd=cmds.strip()
print strip_cmd
stdin,stdout,stderr = ssh.exec_command(strip_cmd)
for line in stdout.readlines():
print strip_host + "~ " + line.strip()
#ssh.close()
except paramiko.SSHException:
print "Connection Failed"
quit()
ssh.close()
File contents:
Running on machine itself:
cat ip-list
127.0.0.1
localhost
127.0.0.3
cat cmd
ls
Result:
ip route
ls
vm-linux:~/scripts$ ./t.py
127.0.0.1 START OF DEVICE
1
ls
127.0.0.1~ bin
127.0.0.1~ boot
127.0.0.1~ cdrom
127.0.0.1~ dev
127.0.0.1~ etc
127.0.0.1~ home
127.0.0.1~ initrd.img
127.0.0.1~ initrd.img.old
127.0.0.1~ lib
127.0.0.1~ lib64
127.0.0.1~ lost+found
127.0.0.1~ media
127.0.0.1~ mnt
127.0.0.1~ opt
127.0.0.1~ proc
127.0.0.1~ root
127.0.0.1~ run
127.0.0.1~ sbin
127.0.0.1~ snap
127.0.0.1~ srv
127.0.0.1~ sys
127.0.0.1~ tmp
127.0.0.1~ usr
127.0.0.1~ var
127.0.0.1~ vmlinuz
localhost START OF DEVICE
2
127.0.0.3 START OF DEVICE
3