Я хочу импортировать текстовый файл со списком IP-адресов и запустить его со своим скриптом - PullRequest
0 голосов
/ 18 июня 2020

У меня следующий скрипт работает правильно. Это для проверки информации об IP из netbox API. Я хотел бы знать, что добавить, чтобы я мог импортировать список IP-адресов и запустить его для сценария:

#!/bin/python3

import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning

requests.packages.urllib3.disable_warnings(InsecureRequestWarning) #Disable warning for SSL Error

ip_address = input("Enter the IP Address you want to search: ")
apiBaseUrl = "https://netbox.local/api"

headers = {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
    'Authorization': 'Token 5c915999999998ad82112b3b5880199769894421' #Here you can add your own token
}

def get_hostInterfaceDescription(ip4):
    resp = requests.get(apiBaseUrl + '/ipam/ip-addresses/?q=' + ip4,headers=headers,verify=False).json()
    return resp['results'][0]["description"] #this gets the description information
try:
    desc = get_hostInterfaceDescription(ip_address)
    print("")
    print("Description found in Netbox: " + desc)
except TypeError or IndexError:
    print("Description Not found")

def get_hostInterfaceTenant(ip4):
    resp = requests.get(apiBaseUrl + '/ipam/ip-addresses/?q=' + ip4,headers=headers,verify=False).json()
    return resp['results'][0]["tenant"]["name"] #this gets the description information
try:
    tenant = get_hostInterfaceTenant(ip_address)
    print("")
    print("Tenant found in Netbox: " + tenant)
except TypeError or IndexError:
    print("Tenant Not found")

def get_hostInterfaceVRF(ip4):
    resp = requests.get(apiBaseUrl + '/ipam/ip-addresses/?q=' + ip4, headers=headers, verify=False).json()
    return resp['results'][0]["tenant"]["name"]  # this gets the description information
try:
    vrf = get_hostInterfaceVRF(ip_address)
    print("")
    print("VRF found in Netbox: " + vrf)
except TypeError or IndexError:
    print("VRF Not Found")

1 Ответ

0 голосов
/ 18 июня 2020

Загрузить текстовый файл и перебрать его содержимое очень просто в Python:

with open("ip_list.txt") as ip_list:
    for address in ip_list:
        address = address.strip()  # remove trailing newline
        do_something_with(address)

В вашем случае do_something_with может выглядеть так:

def do_something_with(ip4):
    try:
        desc = get_hostInterfaceDescription(ip4)
        ...
    except ...:
        ...

    try:
        tenant = get_hostInterfaceTenant(ip4)
        ...
    except ...:
        ...

    ...
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...