【问题标题】:Using Paramiko SSH module with csv.reader?将 Paramiko SSH 模块与 csv.reader 一起使用?
【发布时间】:2020-05-17 17:43:14
【问题描述】:

我目前正在使用 paramiko 模块通过 SSH 连接到以 .csv 文件形式提供的 IP 地址列表,然后将命令推送到这些 IP。为此,我使用 csv.reader() 打开并读取以下格式的文件的 100 行。

序列号、IP 地址、MS、RM(MS 和 RM 是与 IP 地址相关的信息)

背景

这是我使用 csv.reader() 打开和读取文件的地方,然后将信息作为字典放置keys

然后我在keys 中嵌套另一个字典为keys[row[0]],以索引IP 地址和其他信息为ep_ipms_keyrm_key

option_dict = open('OptionKeyDict.csv','r')
reader= csv.reader(option_dict)

keys= {}

for row in reader:
    keys[row[0]]= {'IP':row[1],'MS': row[2],'RM': row[3]}

ep_ip = keys[row[0]]['IP']
ms_key= keys[row[0]]['MS']
rm_key= keys[row[0]]['RM']

command= 'xCommand SystemUnit OptionKey Add Key: '

multi_site= command + ms_key
remote_monitor= command + rm_key

然后我继续介绍脚本的Paramiko逻辑,将上面的语句和SSH转换成IP地址,然后执行multi-site & remote-monitor命令。

for host in keys:
    host= ep_ip
    i = 1

    while True:
        print ("\nTrying to connect to %s (%i/2)" % (host, i))

        try:
           ssh = paramiko.SSHClient()
           ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
           ssh.connect(host, username=username, password=password, look_for_keys=False, timeout= 5)
           print ("\nConnected to %s" % host )
           connection_state = 1
           break

    if connection_state == 1:
        client_shell = ssh.invoke_shell()
        time.sleep(.4)
        client_shell.send(multi_site + "\n")
        time.sleep(.4)
        client_shell.send(remote_monitor + "\n")

所以,运行它部分工作。该脚本成功 SSH 然后推送命令,但它仅使用最后一行的信息(IP 地址、MS 和 RM)并运行 100 次,因为 .csv 中有 100 行。

我似乎无法让脚本从第一行开始,然后沿着每一行一直到第 100 行。

现在我已经把上下文弄明白了......(抱歉,StackOverflow 的新手)

问题

我在这里缺少什么会导致这种情况发生?我觉得这是一个我没有看到的简单调整。

我们将不胜感激任何和所有反馈。 谢谢!

【问题讨论】:

    标签: python csv dictionary for-loop paramiko


    【解决方案1】:

    您根本没有在for host in keys: 循环中使用host 变量。

    您实际上可以在直接读取数据时使用这些数据。看来您根本不需要将数据收集到keys

    for row in reader:
        host = row[1]
        ms_key = row[2]
        rm_key = row[3]
    
        i = 1
    
        while True:
            print ("\nTrying to connect to %s (%i/2)" % (host, i))
    
            try:
               ssh = paramiko.SSHClient()
               ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
               ssh.connect(
                   host, username=username, password=password, look_for_keys=False, timeout= 5)
               print ("\nConnected to %s" % host )
               connection_state = 1
               break
    
        if connection_state == 1:
            client_shell = ssh.invoke_shell()
            time.sleep(.4)
            client_shell.send(multi_site + "\n")
            time.sleep(.4)
            client_shell.send(remote_monitor + "\n")
    

    (顺便说一句,i 从未改变其初始值 1

    【讨论】:

    • 感谢马丁的回复!我明白你在说什么。看起来我在不需要的时候采取了额外的步骤。 'i' 值也很好捕捉!将进行这些更改。
    猜你喜欢
    • 2019-05-09
    • 2011-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-03
    • 2017-08-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多