多執行緒監測區域網內主機的每晚關機情況並記錄在Excel表格內
阿新 • • 發佈:2020-08-01
#coding:utf-8 import subprocess,threading,time,os R = threading.Lock() #執行緒鎖 threa_num = 100 #執行緒數 from openpyxl import load_workbook from openpyxl.styles import Font, colors, Alignment font_color_red = Font(color=colors.RED) font_color_green = Font(color=colors.GREEN) # print(os.path.join(os.getcwd(),os.listdir()[1])) file = "ip.xlsx" # file = os.path.join(os.getcwd(),"ip.xlsx") def check_alive(ip): result = subprocess.call('ping -w 1000 -n 1 %s' %ip,stdout=subprocess.PIPE,shell=True) #ubuntu: ping -c1 -i0.3 -W1 %s windows: ping -w 1000 -n 1 %s if result == 0: # h = subprocess.getoutput('ping ' + ip) # returnnum = h.split('平均 = ')[1] # print('\033[32m%s\033[0m 能ping通,延遲平均值為:%s' %(ip,returnnum)) return True else: return False # print('\033[31m%s\033[0m ping 不通!' % ip) def write_xlsx(ip,row,max_col): if check_alive(ip): print('%s 線上!' %(ip)) # print('\033[32m%s\033[0m 線上!' %(ip)) with R: sheet.cell(row = row, column = max_col).value = "線上" sheet.cell(row = row, column = max_col).font = font_color_green else: print('%s 不線上!' % ip) # print('\033[31m%s\033[0m 不線上!' % ip) with R: sheet.cell(row = row, column = max_col).value = "不線上" sheet.cell(row = row, column = max_col).font = font_color_red pass if __name__ == '__main__': wb = load_workbook(file) # print(wb.get_sheet_names()) # 獲得所有sheet的名稱 sheet = wb.get_sheet_by_name('Sheet1') # 根據sheet名字獲得sheet max_row = sheet.max_column+1 for row in range(1,sheet.max_row+1): if row == 1: sheet.row_dimensions[max_row].width = 120 sheet.cell(row = row, column = max_row).value = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) continue # print(sheet.cell(row = row, column = 1).value) threading.Thread(target=write_xlsx,args=(sheet.cell(row = row, column = 1).value,row,max_row,)).start() while True: if len(threading.enumerate())>threa_num: #程序數 time.sleep(5) else: break while True: if len(threading.enumerate())>=2: #程序數 time.sleep(2) else: wb.save(file) print("儲存完成".center(30,"-")) break quit()