简体   繁体   English

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

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

I am currently trying to get ip address from text. 我目前正在尝试从文本获取IP地址。 But the code I tried is only getting the last line from the file. 但是我尝试的代码仅从文件中获取最后一行。 I am using the following code 我正在使用以下代码

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

help would be appreciated 帮助将不胜感激

Update: 更新:

When I removed except 当我删除时

I got the following error 我收到以下错误

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

ssh_client.connect(hostname=host,username=user,password=password) ssh_client.connect(主机名=主机,用户名=用户,密码=密码)

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

Can some one help me out ? 有人可以帮我吗 ?

for line in inp:

will store the next line of inp in line including the terminating new line character '\\n' . 将存储的下一行inpline 包括终止新行字符 '\\n' When you pass this unmodified to ssh_client.connect() , then the host name will include '\\n' . 当您将此未修改的内容传递给ssh_client.connect() ,主机名将包含'\\n' The reason that you get a successful connection with the last line of your input file is very likely that the last line is not terminated by '\\n' . 与输入文件的最后一行成功连接的原因很可能是最后一行没有以'\\n'结尾。

One way to remove the '\\n' is: 删除'\\n'一种方法是:

line = line.strip()

To put it all together, including my comments to your question regarding the recommended use of with : 综上所述,包括我对有关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'

Note: 注意:

I modified your example to work with Python3. 我修改了您的示例以使用Python3。 Some of my changes are probably not necessary for Python2. 我的一些更改对于Python2可能不是必需的。 If you are not forced to use Python2, I would always recommend to use Python3 for new projects. 如果您不被迫使用Python2,我总是建议对新项目使用Python3。 See End of support for python 2.7? 请参阅终止对python 2.7的支持?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM