0

I wrote a code to ssh to a server an execute a command, I now need to pass IPs from a file to ssh and run the same commands.

I used paramiko as an ssh client, in client.connect I gave hostname statically, I would like to pick one IP at a time from a text file and execute the same program.

import paramiko
import logging
import sys
logging.basicConfig(level=logging.INFO)
    def EsxCli():
        client = paramiko.SSHClient()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy) client.connect(hostname='192.168.110.41',port='22',username='root',password='VMware1!',look_for_keys=False)
        stdin,stdout,stderr = client.exec_command('/etc/init.d/vShield-Stateful-Firewall status')
        output_read = stdout.read()
        if 'vShield-Stateful-Firewall is running' in str(output_read):
        logging.info('\nService is already running!')
        sys.exit(1)
        elif 'vShield-Stateful-Firewall is not running' in str(output_read):
            logging.info('\nService is down, STARTING IT NOW')
            stdin, stdout, stderr = client.exec_command('/etc/init.d/vShield-Stateful-Firewall start')
            service_status = stdout.read()
            logging.info(str(service_status))
        else:
            logging.exception('SSH Timed OUT')
            sys.exit(1)
EsxCli()

The same code has to be executed for multiple hostnames. say 192.168.110.41 to 192.168.110.200

  • So what does your text file contain? List of IPs (192.168.110.41, 192.168.110.42, 192.168.110.43, ...) ? Or some kind of IP range (192.168.110.41-192.168.110.200)? – Martin Prikryl Jan 09 '19 at 17:02
  • it contains list of IPs. –  Jan 21 '19 at 12:34
  • OK, that you question has nothing to do with Paramiko and is basically a duplicate to [How to read a file line-by-line into a list?](https://stackoverflow.com/q/3277503/850848) – Martin Prikryl Jan 21 '19 at 13:14

1 Answers1

0

I have been able to complete this. Converted the file into a python LIST.

ip = r'iplist.txt'
iplist=[line.strip() for line in open('iplist.txt')]
print(iplist)

Below is the script.

https://github.com/anudeep404/vmware_automation/blob/v1/service_restart_4_service_restart.py