从文本文件中提取 IP 地址并将其用作 Python 中的输入

extracting IP address from text file and use them as input in Python

我目前正在尝试从文本中获取 IP 地址。但是我尝试的代码只是从文件中获取最后一行。我正在使用以下代码

import paramiko
import time
import getpass
import sys
import socket
import re

user = raw_input("Enter you username: ")
password = getpass.getpass()
inp = open(r'ipaddressrouter.txt', 'r') 


for line in inp:
    try:
        ssh_client = paramiko.SSHClient()
        ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh_client.connect(hostname=line,username=user,password=password)
        print "Successful Connection to " + line + '\n'
        stdin, stdout, stderr = ssh_client.exec_command('sh ip int b \n')
        output = stdout.read()
        out = open('out.txt', 'a')
        out.write(line + '\n')  
        out.write(output + '\n')
        out.write('\n')
    except (socket.error, paramiko.AuthenticationException):
            status = 'fail' 

ssh_client.close

不胜感激

更新:

当我删除 except

我收到以下错误

文件 "C:\Users\abc\Desktop\Python Test Scripts\newstest2.py",第 20 行,位于

ssh_client.connect(主机名=主机,用户名=用户,密码=密码)

文件 "C:\Python27\lib\site-packages\paramiko\client.py",第 329 行,在连接中 to_try = list(self._families_and_addresses(hostname, port)) 文件 "C:\Python27\lib\site-packages\paramiko\client.py",第 200 行,在 _families_and_addresses 主机名,端口,socket.AF_UNSPEC,socket.SOCK_STREAM)socket.gaierror:[Errno 11004] getaddrinfo 失败

有人能帮帮我吗?

import re
lis_of_ip = ['10.1.1.1','10.1.1']
for ip in lis_of_ip:
    if(re.match('((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(?:\.|$)){4}', ip)):
        print(ip,'true')
    else:
        print(ip,'false')
for line in inp:

inp 的下一行存储在 line 中,包括终止换行符 '\n'。当您将此未修改的传递给 ssh_client.connect() 时,主机名将包含 '\n'。您与输入文件的最后一行成功连接的原因很可能是最后一行没有被 '\n'.

终止

删除 '\n' 的一种方法是:

line = line.strip()

综上所述,包括我对您关于 with 的推荐使用问题的评论:

import socket

import paramiko

# get user/password as in the question code (not repeated here)
# ....

status = 'OK'

with open(r'ipaddressrouter.txt', 'r') as inp:
    for line in inp:
        line = line.strip()
        with paramiko.SSHClient() as ssh_client:
            ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            try:
                ssh_client.connect(hostname=line, username=user, password=password)
                print("Successful Connection to " + line)
                stdin, stdout, stderr = ssh_client.exec_command('target command here')
                output = stdout.read()
                with open('out.txt', 'a') as out:
                    out.write(line + '\n')
                    out.write(str(output, encoding='utf-8') + '\n')
                    out.write('\n')
            except (socket.error, paramiko.AuthenticationException) as e:
                print("Failed connection to " + line)
                status = 'fail'

注:

我修改了您的示例以使用 Python3。 Python2 可能不需要我的一些更改。如果你不是被迫使用 Python2,我总是建议对新项目使用 Python3。参见 End of support for python 2.7?