IndexError: list index out of range while connecting to SFTP server using python

IndexError: list index out of range while connecting to SFTP server using python

我写了一个 python 脚本来使用 public 密钥验证连接到 SFTP 服务器。代码从另一个名为 "config file" 的文本文件获取服务器凭据,格式为:

IP,用户名

IP2,用户名2

当配置文件包含超过 5 个 IP 和用户名时,它会抛出错误(见下文)。虽然它不影响输出但是错误的原因是什么以及如何解决它或者有更好的方法来做到这一点

我的代码:

import os
import pysftp
import socket
import paramiko
import time
import os.path
import shutil
import pysftp
import csv
from pathlib import Path
from stat import S_IMODE, S_ISDIR, S_ISREG

cnopts = pysftp.CnOpts()
cnopts.hostkeys=None

import os

privatekeyfile = os.path.expanduser("C:\Users\Rohan\.ssh\cool.prv")
mykey = paramiko.RSAKey.from_private_key_file(privatekeyfile)


config_file_path = "config15.txt"     
file = open(config_file_path, 'r')
reader = csv.reader(file)
all_rows = [row for row in reader]
for line in all_rows:
    server_ip = line[0]
    username = line[1]
    with pysftp.Connection(host=server_ip, username=username, private_key=mykey, cnopts=cnopts) as sftp:
        r = (socket.gethostbyaddr(server_ip))
        print("connection successful with ", r)

输出和错误:(如果配置文件中有 10 个 IP)

connection successful with  ('lootera', [], ['127.0.0.1'])
connection successful with  ('lootera', [], ['127.0.0.1'])
connection successful with  ('lootera', [], ['127.0.0.1'])
connection successful with  ('lootera', [], ['127.0.0.1'])
connection successful with  ('lootera', [], ['127.0.0.1'])
connection successful with  ('lootera', [], ['127.0.0.1'])
connection successful with  ('lootera', [], ['127.0.0.1'])
connection successful with  ('lootera', [], ['127.0.0.1'])
connection successful with  ('lootera', [], ['127.0.0.1'])
Traceback (most recent call last):
  File "C:/Users/Rohan/PycharmProjects/untitled1/m.py", line 30, in <module>
    server_ip = line[0]
IndexError: list index out of range
connection successful with  ('lootera', [], ['127.0.0.1'])

由于我们不知道配置文件,所以我们无法判断那里是否有错误。但是,您可以只检查一行是否包含两个值。这样你就可以避免 IndexError:

for line in all_rows:
    if len(line) != 2:
        continue
    server_ip = line[0]
    username = line[1]

另外:

reader = csv.reader(file)
all_rows = [row for row in reader]
for line in all_rows:

效率很低。为什么不缩短它?

reader = csv.reader(file)
for line in reader: