簡體   English   中英

Python 2D數組和循環

[英]Python 2D array and loop

我是Python的新手,正在嘗試設置腳本來檢查本地網絡上特定的wifi連接的IOT設備的狀態。

本質上,該腳本采用了我要檢查的mac硬件ID。 ping網絡以觸發ARP; 搜索對arp-a的響應以找到相關的Mac ID,如果成功找到,則顯示日期和時間。

兩個問題-1)目前,我只是在其中搜索2個mac地址,但是以后很可能是20個。如何修改我的detect_mac函數以采用二維數組(或類似數組)並遍歷結果為了避免必須重復if any(address in str_output for address in input_address_list1):重復20行。

2)如果我讓此腳本持續運行(運行之間有10分鍾的計時器),此python最終會崩潰嗎? 我是否需要考慮某種垃圾收集,日志溢出等問題?

import pdb, os
import subprocess
import re
import time
from subprocess import Popen, PIPE, DEVNULL

lower=1
upper=25
MAC_address_list1 = ["58:e2:zz:xx:28:d7"]
MAC_address_list2 = ["08:05:xx:zz:75:c5"]
MAC_address_list3 = ["##:##:##:##:##:##"]
MAC_address_list4 = ["##:##:##:##:##:##"]
p = {}

# Get The Current Date and Time
def getdatetime():
    import time
    return time.strftime("%H:%M %d/%m/%Y ")

def detect_mac(input_address_list1, input_address_list2):
    # Assign list of devices on the network to "output"
    output = subprocess.check_output("arp -a", shell=True)

    str_output = output.decode("utf-8")   

    if any(address in str_output for address in input_address_list1):
        print(getdatetime() + str(input_address_list1))

    if any(address in str_output for address in input_address_list2):
        print(getdatetime() + str(input_address_list2))

    #sleep 10 minutes
    time.sleep(600)
    return True


while 1:
    # ping all IPs in range to make ARP available
    for i in range(lower,upper):
        ip = "192.168.1.%d" % i
        p[ip] = Popen(['ping', '-n', '-w5', '-c3', ip], stdout=DEVNULL)

    detect_mac(MAC_address_list1, MAC_address_list2)

我當然可以回答問題1):

import pdb, s
import subprocess
import re
import time
from subprocess import Popen, PIPE, DEVNULL

lower=1
upper=25
MAC_address_list1 = ["58:e2:zz:xx:28:d7"]
MAC_address_list2 = ["08:05:xx:zz:75:c5"]
MAC_address_list3 = ["##:##:##:##:##:##"]
MAC_address_list4 = ["##:##:##:##:##:##"]

MAC_addresses = ([MAC_address_list1],[MAC_address_list2])

[...]

def detect_mac(input_address_list):
  # Assign list of devices on the network to "output"
  output = subprocess.check_output("arp -a", shell=True)

  str_output = output.decode("utf-8")   

  for address_list in input_address_list:

    if any(address[0] in str_output for address in address_list):
        print(getdatetime() + str(address_list))



  #sleep 10 minutes
  time.sleep(600)
  return True

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM