1、背景
當前項目在網線插拔時 需要重啓一些服務。因此通過ethtool eth0命令來獲取網口的狀態。
#!/usr/bin/env python3
# coding=utf-8
# create at 2019-11-06
import subprocess
import threading
class MonitorNetwork:
'用於網絡狀態監聽 發送給主模塊 用於服務重啓'
'''
傳入要監聽的端口號
'''
name = [0];
def callBack(self, change):
print("我是回調函數!")
'''
保存狀態 用於緩存要監聽的每個端口的狀態
'''
status = [];
'''
初始化函數 接收要監聽的端口號 以數組形式傳入 [0, 1, 2, 3...]等等
'''
def __init__(self, name, callBack):
self.name = name;
self.callBack = callBack;
# 調用監聽函數
self.MonitorNetworkStatus();
"""
根據接口名稱獲取接口信息
"""
def getEthtool(self):
# val = os.system('ethtool eth' + str(name) + '| grep Link');
list = [];
for _name in self.name:
p = subprocess.Popen(["ethtool eth" + str(_name) + " | grep Link | awk {'print $3'}"], shell=True,
stdout=subprocess.PIPE).communicate()
# 二維數組 0位保存的是監控的端口號 1位是狀態
list.append([_name, bool(p[0])]);
return list;
"""
監聽端口線程啓動
timer 用於對外暴露線程終止
"""
timer = None;
def MonitorNetworkStatus(self):
statusArr = self.getEthtool();
change = [];
print(statusArr)
for i in range(0, len(statusArr)):
_status = statusArr[i];
if bool(len(_status)) & len(self.status) == len(_status):
if (_status[1] != self.status[i][1]):
change.append(_status);
self.status[i][1] = _status[1];
else:
self.status.append(_status);
if bool(len(change)):
# 將change發送出去
self.callBack(change);
print('發送消息');
self.timer = threading.Timer(6000, self.MonitorNetworkStatus);
self.timer.start()
'''
線程終止 停止監控
'''
def stopMonitor(self):
self.timer.join()
# ntArr = [0, 1];
#
# def callBack(change):
# print("123");
#
# nt = MonitorNetwork(ntArr, callBack);