sonashii
sonashii

Reputation: 19

Executing SSH command over list of IP addresses (using Paramiko)

First time post as I am incredibly new to Python, but I've encountered an issue that I am needing help with - please forgive me if my code seems a little rudimentary.

Using Paramiko, I've built a custom SSH client for business use - the end game is to have it perform a given command (reboot given as an example) over a list of IP addresses (parsed from a text file) in sequence.

For the Paramiko section:

import paramiko
import sys
import os
import time

port = 22

def ssh_comm(ip, user, password, cmd):
     try:
        client = paramiko.SSHClient()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        client.connect(ip, username='username', password='password')
        ssh_session = client.get_transport().open_session()
        if ssh_session.active:
           ssh_session.exec_command(cmd),
           buffer = (ssh_session.recv(4096)).decode("utf-8")
           print (buffer)
     except paramiko.AuthenticationException:
        ssh_comm2(ip, user, password, cmd) **#TRIES NEXT SET OF CREDENTIALS**

def cmd_loop_ssh():
        while True:
                cmd = input('Command: ')
                ssh_comm(ip, user, password, cmd)

ip = input('IP: ')
cmd_loop_ssh()

This works fine for executing commands over one machine, but I need it to perform over several - I can parse the IP's I need from a formatted text file as follows:

iplist = '\IP TEXT FILE LOCATION.txt\'
    with open(iplist, 'r') as fp:
        line = fp.readline()
        while line:
            print ('{}'.format(line.strip()))
            line = fp.readline()

Again, very new to this - any help would be greatly appreciated!

Upvotes: 1

Views: 3702

Answers (1)

Nathan Vērzemnieks
Nathan Vērzemnieks

Reputation: 5603

First off, you can more cleanly read your IP address file like this:

with open(iplist) as fp:
    ips = [line.strip() for line in fp]

Then I think all you need to do is put that block inside your cmd_loop_ssh, before the while loop, and then replace

ssh_comm(ip, user, password, cmd)

with

for ip in ips:
    ssh_comm(ip, user, password, cmd)

You might also want to add a command to quit:

cmd = input('Command: ')
if cmd == 'quit':
    break
else:
    for ip in ips:
        ssh_comm(ip, user, password, cmd)

Upvotes: 1

Related Questions