检测IP地址变化状态

时间:2019-08-08 20:01:07

标签: python python-3.x networking

我有这段代码,可以显示网络上的ip地址以及mac地址和状态。我让它在此循环中运行,因此它总是更新。我如何拥有它,以便当它更新并且离线的ip地址联机时,在一个周期内它会显示“ New”而不是“ on”,然后在下一个周期在线显示(如果它仍处于活动状态)。

import os

from getmac import get_mac_address

class bcolors:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'

minr = int(input("Starting Ip: "))
maxr = int(input("Ending Ip: "))


while True:

    for num in range(minr, maxr + 1): #plus one is to include the last digit entered
        ip = "192.168.2." + str(num)

        from getmac import getmac

        exit_code = os.system("ping -n 1 -w 1 " + ip + " > nul") # Windows
        #exit_code = os.system("ping -c 1 -W 1 " + ip + " > /dev/null") # Linux

        getmac.PORT = 44444  # Default: 55555

        if exit_code == 0:
            print(ip, bcolors.OKGREEN + "ONLINE " + bcolors.ENDC + bcolors.OKBLUE + get_mac_address(ip=ip, network_request=True) + bcolors.ENDC)

        elif (ip == '192.168.2.' + str(maxr + 1) and exit_code == 0):
            print('192.168.2.' + str(maxr), bcolors.OKGREEN + "ONLINE " + bcolors.ENDC + bcolors.OKBLUE + get_mac_address(ip=ip, network_request=True) + bcolors.ENDC)
            print("")
            print(bcolors.HEADER + "Beginning" + bcolors.ENDC)
            print("")

        elif (ip == '192.168.2.' + str(maxr)):
            print('192.168.2.' + str(maxr), bcolors.FAIL + "OFFLINE" + bcolors.ENDC)
            print("")
            print(bcolors.HEADER + "Refreshed" + bcolors.ENDC)
            print("")

        else:
            print(ip, bcolors.FAIL + "OFFLINE" + bcolors.ENDC)

应该发生的是,如果IP联机,它将显示新的,而在下一个周期联机。

0 个答案:

没有答案