Вопрос новичка: вход в цикл while - PullRequest
0 голосов
/ 27 мая 2020

сначала позвольте мне просто повторить, что я полный нуб с python и программированием в целом. Я фанат сетей / систем, которому нужно что-то автоматизировать.

У меня есть сетевая платформа meraki, и я реализовал следующий сценарий для включения чего-то, что называется IPSe c Failover: https://documentation.meraki.com/MX/Site-to-site_VPN/Tag-Based_IPsec_VPN_Failover#Code

Я прочитал код, понял его , добавил кучу комментариев, чтобы помочь мне изучить построчно, а затем добавил / изменил операторы печати, чтобы я мог знать, что он делает. У меня есть сценарий, который запускается при запуске через systemd, но я хочу вести журнал.

Я пробовал несколько руководств по ведению журнала, и хотя они действительно работают за пределами while l oop, внутри - нет. В то время как l oop никогда не кончится, никогда. Он всегда работает, всегда следит за тем, чтобы переключить туннель. Я не понимаю, что делать, чтобы журнал работал, пока l oop :( И снова мои навыки python очень плохие. Я прочитал документацию по ведению журнала и понимаю три основных типа: systemd, syslog, файл согласно https://www.loggly.com/ultimate-guide/python-logging-basics/ Пожалуйста, помогите

#!/usr/bin/python3
import requests, json, time
import logging

logger = logging.getLogger()
formatter = logging.Formatter(
        '%(asctime)s %(name)-12s %(levelname)-8s %(message)s')

#####

# define your API key, the URL we need for loss and latency as well as our HTML header
api_key = '00000'
url = 'https://api.meraki.com/api/v0/organizations/00000/uplinksLossAndLatency'
header = {"X-Cisco-Meraki-API-Key": api_key, "Content-Type": "application/json"}

# define an array to work with
networkDownList = []

while True:    
    # load the data we need from our "url" above into a variable called response
    response = requests.get(url,headers=header)
    # rip through the different networks in json format, assigned to variable 'network'
    for network in response.json():
        #first setup our logging
        fileh = logging.FileHandler('/tmp/logfile', 'a')
        fileh.setFormatter(formatter)
        # remove all old handlers
        for hdlr in logger.handlers[:]: 
            logger.removeHandler(hdlr)
        logger.addHandler(fileh)
        # match the uplink itself as well as the Google uplink statistic check
        if network['ip'] != '8.8.8.8' and network['uplink'] == "wan1":
            # print the network ID and IP 
            logger.info("Beginning Check on Network ID:",network['networkId'])
            logger.info("Remote Connectivity IP:",network['ip'])
            # collect information on the network variable we're currently processing, we're looking for the name and the tags assigned to it.
            network_info = requests.get("https://api.meraki.com/api/v0/networks/"+network['networkId'], headers=header)
            # check to see the networkID is in the networkDownList (this script may have been interrupted - je)
            tags = network_info.json()['tags'].split(' ')
            if "_primary_down" in tags[1] or "_primary_down" in tags[2]:
                if not network['networkId'] in networkDownList:
                    logging.warning("WARNING: Tags are set to secondary, did not find networkID in networkDownList, adding now...")
                    networkDownList.append(network['networkId'])
            # set a control variable called loss to false
            loss=False
            # find the current state of the tunnel based on the tags
            # go through the data in our 'network' variable and if the loss is ever greater than 30%
            for iteration in network['timeSeries']:
                if iteration['lossPercent'] >= 30:
                    # set the control variable to true
                    loss=True
                    # print the name of the network and the tags and the packet loss percentage
                    print("WARNING: Packet Loss Found")
                    print("Network Name:",network_info.json()['name'])
                    print("Network Tags:",network_info.json()['tags'])
                    print("Packet Loss:",iteration['lossPercent'],"%")
                    # load the tags for the network into a variable and split them
                    tags = network_info.json()['tags'].split(' ')
                    # search for primary_down tag to see if the VPN is already swapped
                    if "_primary_down" in tags[1] or "_primary_down" in tags[2]:
                        print("VPN already swapped.")
                        print("Network Down List:",networkDownList)
                        # start the while loop over
                        break
                    # if primary is down and not swapped already start the swap process, this means splitting all the tags with primary_up and backup_down and reversing them to backup_up primary_down
                    else:
                        print("INFO: Changing Tags...")
                        if "_primary_up" in tags[1]:
                            tags[1] = tags[1].split("_up")[0]+"_down"
                        if "_primary_up" in tags[2]:
                            tags[2] = tags[2].split("_up")[0]+"_down"
                        if "_backup_down" in tags[1]:
                            tags[1] = tags[1].split("_down")[0]+"_up"
                        if "_backup_down" in tags[2]:
                            tags[2] = tags[2].split("_down")[0]+"_up"
                        # create a payload variable with our new tags
                        payload = {'tags': tags[2]+" "+tags[1]}
                        # push the payload variable to the meraki cloud
                        new_network_info = requests.put("https://api.meraki.com/api/v0/networks/"+network['networkId'], data=json.dumps(payload), headers=header)
                        # add the network ID to the network down list
                        networkDownList.append(network['networkId'])
                        # print the list
                        print("Change complete!")
                        print("Network Down List:",networkDownList)
                        #alert us
                        #trueEmail()
                        # start the while loop over
                        break
            # If the previous if statement was not true but false instead AND the network ID is in the networkDownList then its time to swap back            
            if loss==False and network['networkId'] in networkDownList:
               print("Remote Connectivity IP:",network['ip'])
               print("Packet Loss:",iteration['lossPercent'],"%")
               print("Primary VPN healthy again..swapping back")
               # collect information on the network variable we're currently processing, we're looking for the name and the tags assigned to it.
               network_info = requests.get("https://api.meraki.com/api/v0/networks/"+network['networkId'], headers=header)
               # make the tags variable and then swap all backup_up and primary_down to primary_up and backup_down
               print("INFO: Changing Tags...")
               tags = network_info.json()['tags'].split(' ')
               if "_primary_down" in tags[1]:
                   tags[1] = tags[1].split("_down")[0]+"_up" 
               if "_primary_down" in tags[2]:
                   tags[2] = tags[2].split("_down")[0]+"_up" 
               if "_backup_up" in tags[1]:
                   tags[1] = tags[1].split("_up")[0]+"_down"
               if "_backup_up" in tags[2]:
                   tags[2] = tags[2].split("_up")[0]+"_down"
               # create a payload variable with our new tags
               payload = {'tags': tags[1]+" "+tags[2]}
               # push the payload variable to the meraki cloud
               new_network_info = requests.put("https://api.meraki.com/api/v0/networks/"+network['networkId'], data=json.dumps(payload), headers=header)
               # remove the networkID from the network Down List
               networkDownList.remove(network['networkId'])
               print("Change complete!")
               print("Network Down List:",networkDownList)
               #alert us
               #falseEmail()
    print("Sleeping for 90s...")
    time.sleep(90)
...