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

时间:2018-07-05 15:51:36

标签: python file-handling

我目前正在尝试从文本获取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

我们将不胜感激

更新:

当我删除时

我遇到以下错误

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

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

connect to_try = list(self._families_and_addresses(hostname,port))中的文件“ C:\ Python27 \ lib \ site-packages \ paramiko \ client.py”,第329行 文件“ C:\ Python27 \ lib \ site-packages \ paramiko \ client.py”,第200行,位于_families_and_addresses主机名,端口,套接字。AF_UNSPEC,socket.SOCK_STREAM)socket.gaierror:[Errno 11004] getaddrinfo失败

有人可以帮我吗?

2 个答案:

答案 0 :(得分:1)

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?

答案 1 :(得分:0)

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