多线程监测局域网内主机的每晚关机情况并记录在Excel表格内
#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()