首页 > 解决方案 > 从文本文件中提取 IP 地址并将其用作 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

帮助将不胜感激

更新:

当我删除除了

我收到以下错误

文件“C:\Users\abc\Desktop\Python Test Scripts\newstest2.py”,第 20 行,在

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

文件“C:\Python27\lib\site-packages\paramiko\client.py”,第 329 行,在 connect 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 failed

有人可以帮我吗 ?

标签: pythonfile-handling

解决方案


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。请参阅对 python 2.7 的支持结束?


推荐阅读