从文件输入到paramiko

时间:2019-01-09 16:47:57

标签: python-3.x function iteration paramiko

我写了一条代码ssh到服务器并执行命令,现在我需要将IP从文件传递到ssh并运行相同的命令。

我使用paramiko作为ssh客户端,在client.connect中,我静态地提供了主机名,我想一次从文本文件中选择一个IP,然后执行相同的程序。

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()

必须对多个主机名执行相同的代码。 说192.168.110.41到192.168.110.200

1 个答案:

答案 0 :(得分:0)

我已经能够完成此操作。将文件转换为python LIST。

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

下面是脚本。

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