def ping_router(Device, Action, Peer_IP, Count="5"): print(Action) device_data = getdata.get_data() IP_add = device_data['Device_Details'][Device]['ip_add'] Port_no = device_data['Device_Details'][Device]['port'] child = pexpect.spawn('telnet ' + IP_add + ' ' + Port_no) clear_buffer.flushBuffer(5, child) if child: child.sendcontrol('m') child.sendcontrol('m') flag = child.expect(['PC-1>*', 'root*', pexpect.EOF, pexpect.TIMEOUT], timeout=50) if flag in (0, 1): configs = "ping %s -c %s " % (Peer_IP, Count) commands = configs.split('\n') execute.execute(child, commands) resp = child.before.decode('utf-8') child.sendcontrol('m') child.sendcontrol('m') regex = r'bytes from %s' %(Peer_IP) if re.search(regex, resp): return True else: return False else: return False
def CVtrain(dataset, task, architecture, epochs, batch_size, optimizer, rate, viz, num, PATH): trainloader, testloader = get_data(dataset, batch_size, num) # define architecture logdir = "logs/" + datetime.now().strftime("%Y%m%d-%H%M%S") print('log file for Tensor Board at ', logdir) # print(net) if PATH is None: net = get_arch(architecture, trainloader) trained_net = lets_train(trainloader, testloader, task, net, epochs, optimizer, rate, logdir) else: # PATH = './data/abc.pth' # torch.save(trained_net, PATH) # print(PATH) device = torch.device("cuda" if torch.cuda.is_available() else "cpu") trained_net = torch.load(PATH).to(device) # accuracy = lets_test(testloader, trained_net) create_graph_viz(trained_net, trainloader, logdir) create_3d_projector(testloader, num, trained_net, logdir, cm=True) json_output = serve_json(testloader, trained_net, viz, num) return json_output
def Login(self, Device, child): child.sendcontrol('m') device_data = getdata.get_data() hostname = device_data['Device_Details'][Device]['Hostname'] Password = device_data['Device_Details'][Device]['pwd'] clear_buffer.flushBuffer(5, child) child.sendcontrol('m') flag = child.expect([ 'Router>', 'Router#', hostname + '>', hostname + '#', pexpect.EOF, pexpect.TIMEOUT ], timeout=50) if flag == 0 or flag == 2: child.send('enable') child.sendcontrol('m') child.send(Password) child.sendcontrol('m') clear_buffer.flushBuffer(5, child) child.sendcontrol('m') child.sendcontrol('m') child.sendcontrol('m') flag1 = child.expect([ hostname + '>', hostname + '#', 'Router#', pexpect.EOF, pexpect.TIMEOUT ], timeout=50) if flag1 == 0: self.Login(Device, child) return
def connect(self, Device): device_data = getdata.get_data() IP_add = device_data['Device_Details'][Device]['ip_add'] Port_no = device_data['Device_Details'][Device]['port'] Password = device_data['Device_Details'][Device]['pwd'] hostname = device_data['Device_Details'][Device]['Hostname'] child = pexpect.spawn('telnet ' + IP_add + ' ' + Port_no) child.sendcontrol('m') child.sendcontrol('m') clear_buffer.flushBuffer(5, child) child.sendcontrol('m') child.sendcontrol('m') child.sendcontrol('m') flag = child.expect([ 'Router>', 'Router#', hostname + '>', hostname + '#', pexpect.EOF, pexpect.TIMEOUT ], timeout=50) if (flag == 0 or flag == 1 or flag == 2 or flag == 3): self.Login(Device, child) if flag == 4: return False if flag == 5: self.connect(Device) return child
def set_IP_Host(self, Device, Action, Mask): # import sys, pdb; pdb.Pdb(stdout=sys.__stdout__).set_trace() device_data = getdata.get_data() IP_add = device_data['Device_Details'][Device]['ip_add'] Network = device_data['Device_Details'][Device]['network'] Port_no = device_data['Device_Details'][Device]['port'] Gateway = device_data['Device_Details'][Device]['gateway'] child = pexpect.spawn('telnet ' + IP_add + ' ' + Port_no) clear_buffer.flushBuffer(1, child) if child: child.sendcontrol('m') child.sendcontrol('m') flag = child.expect(['PC*', pexpect.EOF, pexpect.TIMEOUT], timeout=50) if flag == 0: if Action == 'configure': configs = "ip %s %s %s""" % (Network, Mask, Gateway) commands = configs.split('\n') execute.execute(child, commands) child.sendcontrol('m') else: unconfig = "clear ip" commands = unconfig.split('\n') execute.execute(child, commands) child.sendline('exit') child.sendcontrol('m') return True else: return False
def batch_predict(self, P, S1, S2, Q, n): preds = [] num = 0 _, _, triple_total = getdata.get_data(self.ent_path) for start in range(0, n, self.batch_size): end = start + self.batch_size p = P[start:end] s1 = S1[start:end] s2 = S2[start:end] q = Q[start:end] # pos_h_batch, pos_r_batch, pos_t_batch, neg_h_batch, neg_r_batch, neg_t_batch = getdata.get_batch(self.ebatch_size, self.ent_path, triple_total) items, attrs = getdata.getdatas(self.ebatch_size, self.itemattrs, self.totalitem) # for item in [pos_h_batch, pos_r_batch, pos_t_batch, neg_h_batch, neg_r_batch, neg_t_batch]: # item = item[:len(p)] # pred= self.model.predict(p, s, q, self.relations, pos_h_batch, pos_r_batch, pos_t_batch, neg_h_batch, neg_r_batch, neg_t_batch) pred = self.model.predict(p, s1, s2, q, self.relations, items, attrs) # if num < 3: # for i in range(len(pred[0])): # qq = [w for x in q[i] if x!=0 for w in self.word_idx if self.word_idx[w]==x] # aa = self.candidates[pred[0][i]] # print('-'+(' ').join(qq).replace(" ' ","'")) # print('-'+(' ').join(aa).replace(" ' ","'")) # num += 1 preds += list(pred[0]) return preds
def main(): load_model = False model_save = "data/xgb.dat" (x, y), (x_t, y_t) = getdata.get_data(size=1000000, test_size=0.05) print "x shape is ", x.shape # x=x.reshape((-1,input_size,1)) # x_t=x_t.reshape((-1,input_size,1)) # print "data loaded" # model = getModel() # model.compile(loss="binary_crossentropy",optimizer="Adam",metrics=['accuracy']) # model.fit(x=x,y=y,batch_size=128,epochs=40,validation_data=(x_t,y_t)) # print "model training finished and saved" train_ratio = y.shape[0] / np.sum(y) - 1 if osp.isfile(model_save) and load_model: clf = pickle.load(open(model_save, "rb")) else: clf = xgb.XGBRegressor(max_depth=10, n_estimators=1500, min_child_weight=9, learning_rate=0.05, nthread=8, subsample=0.80, colsample_bytree=0.80, seed=4242, scale_pos_weight=train_ratio) clf.fit(x, y) pickle.dump(clf, open(model_save, "wb")) model = clf print "acry is ", test_accuracy(model, x_t, y_t)
def main(): #获取基础url,爬取数据并存储数据 base_url = "https://movie.douban.com/top250?start=" target_data = gd.get_data(base_url) save_path = "豆瓣电影评分TOP250.xls" db_path = "movie.db" sv.save_data(target_data, save_path) sv.savedb_data(target_data, db_path)
def route(self, Device, AS_id, Interface): device_data = getdata.get_data() hostname = device_data['Device_Details'][Device]['Hostname'] Dev = Devices.Devices() child = Dev.connect(Device) if (child): clear_buffer.flushBuffer(10, child) child.sendcontrol('m') child.sendcontrol('m') child.sendcontrol('m') flag = child.expect([ hostname + '>', hostname + '#', 'Router\>', 'Router\#', pexpect.EOF, pexpect.TIMEOUT ], timeout=90) #print 'flag =%d' % flag if flag == 0 or flag == 2: Dev.Login(Device, child) configs = """ configure terminal router bgp %d neighbor %s next-hop-self end """ % (AS_id, Interface) commands = configs.split('\n') execute.execute(child, commands) #time.sleep(5) child.sendcontrol('m') # print "BGP synchronization enabled in %s " % (Device) if flag == 1 or flag == 3: configs = """ configure terminal router bgp %d neighbor %s next-hop-self end """ % (AS_id, Interface) commands = configs.split('\n') execute.execute(child, commands) #time.sleep(5) child.sendcontrol('m') # print "BGP synchronization enabled in %s " % (Device) #else: # print 'Expected prompt not found' return True else: return False
def index(): if request.method == 'GET': return render_template('index.html') else: #request was a post app.vars['ticker'] = request.form['ticker'] app.vars['results'] = getdata.get_data(app.vars['ticker']) print("length of df: ", len(app.vars['results'])) script, div = bokeh_plot.fig(app.vars['results'], app.vars['ticker']) f = open('%s.txt' % (app.vars['ticker']), 'w') f.write('Ticker: %s\n' % (app.vars['ticker'])) f.close() return render_template('results.html', script=script, div=div)
def btn_klinechartOnButtonClick(self, event): if self.txt_stockcode.GetLineText(0) == "": wx.MessageBox("股票代码不能为空!", "错误", wx.OK | wx.ICON_INFORMATION) elif len(self.txt_stockcode.GetLineText(0)) < 6: wx.MessageBox("输入的股票代码有误!", "错误", wx.OK | wx.ICON_INFORMATION) else: self.data_all = data.get_data(self.txt_stockcode.GetValue(), self.choice_type.GetSelection(), self.spinc_count.GetValue()) if self.data_all is not None: data.show_candlechart(self.data_all['data_list'], self.data_all['sh_symbolName'], self.data_all['sh_code'], self.chkbtn_pic.IsChecked())
def redistribution(self, Device, AS_id, Process_id=None): device_data = getdata.get_data() hostname = device_data['Device_Details'][Device]['Hostname'] Dev = Devices.Devices() child = Dev.connect(Device) if (child): clear_buffer.flushBuffer(10, child) child.sendcontrol('m') child.sendcontrol('m') child.sendcontrol('m') flag = child.expect([ hostname + '>', hostname + '#', 'Router\>', 'Router\#', pexpect.EOF, pexpect.TIMEOUT ], timeout=90) if flag == 0 or flag == 2: Dev.Login(Device, child) configs = """ configure terminal router bgp %d redistribute ospf %d exit router ospf %d redistribute bgp %d subnets end """ % (AS_id, Process_id, Process_id, AS_id) commands = configs.split('\n') execute.execute(child, commands) child.sendcontrol('m') if flag == 1 or flag == 3: configs = """ configure terminal router bgp %d redistribute ospf %d exit router ospf %d redistribute bgp %d subnets end """ % (AS_id, Process_id, Process_id, AS_id) commands = configs.split('\n') execute.execute(child, commands) child.sendcontrol('m') return True else: return False
def checking_operabilty(Device, command): device_data = getdata.get_data() hostname = device_data['Device_Details'][Device]['Hostname'] Dev = Devices.Devices() child = Dev.connect(Device) if child: clear_buffer.flushBuffer(1, child) child.sendcontrol('m') child.sendcontrol('m') child.sendcontrol('m') flag = child.expect([hostname+'>', hostname+'#', 'Router\>', 'Router\#',\ pexpect.EOF, pexpect.TIMEOUT], timeout=90) if flag in (0, 2): Dev.Login(Device, child) configs = """ %s """ % (command) commands = configs.split('\n') execute.execute(child, commands) resp = child.before.decode('utf-8') child.sendcontrol('m') child.sendcontrol('m') regex = r'up' if re.search(regex, resp): return True else: return False if flag in (1, 3): configs = """ %s """ % (command) commands = configs.split('\n') execute.execute(child, commands) resp = child.before.decode('utf-8') child.sendcontrol('m') child.sendcontrol('m') regex = r'up' if re.search(regex, resp): return True else: return False return True else: return False
def Configure_ebgpvrf(self, Device, AS_id, VRF_Name, Interface, neighbor_AS_id, Action): device_data = getdata.get_data() hostname = device_data['Device_Details'][Device]['Hostname'] Dev = Devices.Devices() child = Dev.connect(Device) if child: clear_buffer.flushBuffer(1, child) child.sendcontrol('m') child.sendcontrol('m') child.sendcontrol('m') flag = child.expect([hostname+'>', hostname+'#', 'Router\>', 'Router\#', \ pexpect.EOF, pexpect.TIMEOUT], timeout=90) if flag in (1, 3): Dev.Login(Device, child) if Action == 'enable': configs = """ configure terminal router bgp %d address-family ipv4 vrf %s neighbor %s remote-as %s neighbor %s activate exit-address-family end """ % (AS_id, VRF_Name, Interface, neighbor_AS_id, Interface) commands = configs.split('\n') execute.execute(child, commands) time.sleep(6) child.sendcontrol('m') child.sendline('exit') child.sendcontrol('m') else: unconfig = """ configure terminal no router bgp %s end """ % (AS_id) commands = unconfig.split('\n') execute.execute(child, commands) child.sendcontrol('m') return True else: return False
def Login(self, Device, child): child.sendcontrol('m') device_data = getdata.get_data() hostname = device_data['Device_Details'][Device]['Hostname'] Password = device_data['Device_Details'][Device]['pwd'] clear_buffer.flushBuffer(1, child) if Password != 'zebra': child.sendcontrol('m') flag = child.expect(['Router>', 'Router#', hostname+'>', \ hostname+'#', 'Password*', pexpect.EOF, pexpect.TIMEOUT], timeout=50) if flag in (0, 2): child.send('enable') child.sendcontrol('m') child.send(Password) child.sendcontrol('m') clear_buffer.flushBuffer(1, child) child.sendcontrol('m') child.sendcontrol('m') child.sendcontrol('m') flag1 = child.expect([hostname+'>', hostname+'#', 'Router#', \ pexpect.EOF, pexpect.TIMEOUT], timeout=50) if flag1 == 0: self.Login(Device, child) else: child.send('zebra') child.sendcontrol('m') flag = child.expect(['R*>', pexpect.EOF, pexpect.TIMEOUT], timeout=50) if flag == 0: child.send('enable') child.sendcontrol('m') flag = child.expect(['Password*', pexpect.EOF, pexpect.TIMEOUT], timeout=50) if flag == 0: child.send('zebra') child.sendcontrol('m') child.sendcontrol('m') flag = child.expect(['R*#', pexpect.EOF, pexpect.TIMEOUT], timeout=50) if flag == 0: child.send('show ip route') child.sendcontrol('m') return
def checking_operabilty(Device, command): device_data = getdata.get_data() hostname = device_data['Device_Details'][Device]['Hostname'] Dev = Devices.Devices() child = Dev.connect(Device) if (child): clear_buffer.flushBuffer(10, child) child.sendcontrol('m') child.sendcontrol('m') child.sendcontrol('m') flag = child.expect([ hostname + '>', hostname + '#', 'Router\>', 'Router\#', pexpect.EOF, pexpect.TIMEOUT ], timeout=90) #print 'flag =%d' % flag if flag == 0 or flag == 2: Dev.Login(Device, child) configs = """ %s """ % (command) commands = configs.split('\n') execute.execute(child, commands) #time.sleep(15) child.sendcontrol('m') # print "BGP synchronization enabled in %s " % (Device) if flag == 1 or flag == 3: configs = """ %s """ % (command) commands = configs.split('\n') execute.execute(child, commands) #time.sleep(15) child.sendcontrol('m') # print "BGP synchronization enabled in %s " % (Device) #else: # print 'Expected prompt not found' return True else: return False
def route(self, Device, AS_id, Interface): device_data = getdata.get_data() hostname = device_data['Device_Details'][Device]['Hostname'] Dev = Devices.Devices() child = Dev.connect(Device) if (child): clear_buffer.flushBuffer(10, child) child.sendcontrol('m') child.sendcontrol('m') child.sendcontrol('m') flag = child.expect([ hostname + '>', hostname + '#', 'Router\>', 'Router\#', pexpect.EOF, pexpect.TIMEOUT ], timeout=90) if flag == 0 or flag == 2: Dev.Login(Device, child) configs = """ configure terminal router bgp %d neighbor %s next-hop-self end """ % (AS_id, Interface) commands = configs.split('\n') execute.execute(child, commands) child.sendcontrol('m') if flag == 1 or flag == 3: configs = """ configure terminal router bgp %d neighbor %s next-hop-self end """ % (AS_id, Interface) commands = configs.split('\n') execute.execute(child, commands) child.sendcontrol('m') return True else: return False
def set_loopback(self, Device, Action): device_data = getdata.get_data() hostname = device_data['Device_Details'][Device]['Hostname'] ip_add = device_data['Device_Details'][Device]["ip_add"] child = self.connect(Device) if child != False: clear_buffer.flushBuffer(5, child) child.sendcontrol('m') child.sendcontrol('m') child.sendcontrol('m') child.expect([hostname + '\#', pexpect.EOF, pexpect.TIMEOUT], timeout=60) child.sendcontrol('m') LO_interface_add = device_data['Device_Details'][Device]['lo'] if Action == 'set': configs = """ configure terminal interface %s ip address %s end exit """ % ('loopback0', LO_interface_add) commands = configs.split('\n') execute.execute(child, commands) child.sendcontrol('m') else: unconfig = """ configure terminal interface %s ip address 127.0.0.1 255.255.255.255 end exit """ % ('loopback0') commands = unconfig.split('\n') execute.execute(child, commands) child.sendcontrol('m') child.sendcontrol('m') return True else: return False
def set_IP_DockerHost(self, Device, Action, Mask): # import sys, pdb; pdb.Pdb(stdout=sys.__stdout__).set_trace() device_data = getdata.get_data() IP_add = device_data['Device_Details'][Device]['ip_add'] Network = device_data['Device_Details'][Device]['network'] Port_no = device_data['Device_Details'][Device]['port'] Gateway = device_data['Device_Details'][Device]['gateway'] child = pexpect.spawn('telnet ' + IP_add + ' ' + Port_no) try: clear_buffer.flushBuffer(1, child) except pexpect.exceptions.EOF as exe: print("Unable to reach router prompt") if child: child.sendcontrol('m') child.sendcontrol('m') flag = child.expect(['root*', pexpect.EOF, pexpect.TIMEOUT], timeout=50) if flag == 0: if Action == 'configure': configs = "ifconfig eth0 %s""" % (Network) commands = configs.split('\n') execute.execute(child, commands) child.sendcontrol('m') configs = "route add default gw %s" % (Gateway) commands = configs.split('\n') execute.execute(child, commands) child.sendcontrol('m') else: unconfig = "ifconfig eth0 0" commands = unconfig.split('\n') execute.execute(child, commands) child.sendline('exit') child.sendcontrol('m') return True else: return False
def data2emb(): a = 0.01 data_emb = {} ingredient_emb = np.load("ingredient_emb.npy", allow_pickle=True) train_data, material_index, material_sum, name, id = getdata.get_data() ingredient_dict = count(MAX_VOCAB_SIZE, train_data) # 得到食材字典表,key是食材,value是次数 # print(ingredient_emb.dtype) # print(ingredient_emb) for key in train_data: recipe_emb = {} for ingredient in train_data[key]: emb = ingredient_emb.item().get(ingredient) * a recipe_emb[ingredient] = emb / (a + int(ingredient_dict[ingredient])) recipe = np.zeros(EMBEDDING_SIZE) for ingredient in recipe_emb: recipe = recipe + recipe_emb[ingredient] recipe = recipe / len(recipe_emb) data_emb[key] = recipe np.save("recipe_emb.npy", data_emb) # 将生成的向量保存在字典文件中 return data_emb, train_data, material_index, material_sum, name, id
def enable_syn(self, Device, AS_id): device_data = getdata.get_data() hostname = device_data['Device_Details'][Device]['Hostname'] Dev = Devices.Devices() child = Dev.connect(Device) if child: clear_buffer.flushBuffer(1, child) child.sendcontrol('m') child.sendcontrol('m') child.sendcontrol('m') flag = child.expect([hostname+'>', hostname+'#', 'Router\>', 'Router\#', \ pexpect.EOF, pexpect.TIMEOUT], timeout=90) if flag in (0, 2): Dev.Login(Device, child) configs = """ configure terminal router bgp %d synchronization end """ % (AS_id) commands = configs.split('\n') execute.execute(child, commands) child.sendcontrol('m') if flag in (1, 3): configs = """ configure terminal router bgp %d synchronization end """ % (AS_id) commands = configs.split('\n') execute.execute(child, commands) child.sendcontrol('m') return True else: return False
def init(): global rName global y global p #initialize p and y for r in rName: y.setdefault(r,[]) p.setdefault(r,[]) for s in xrange(S): p[r].append([]) y[r].append([]) for t in xrange(T): p[r][s].append(0) y[r][s].append(0) # print y,p global bids bids=get_data()
def index(): def_id = "98182" if request.method == "POST": def_id = get_id(request.form["cityname"]) if def_id == "none": def_id = "98182" data_dict = get_data(str(def_id)) time = datetime.datetime.now().strftime("%I:%M") date = datetime.date.today().strftime("%B %d, %Y") city_name = data_dict["name"] country_name = data_dict["sys"].get("country") temp = int(data_dict["main"].get("temp") - 273.15) temp_min = int(data_dict["main"].get("temp_min") - 273.15) temp_max = int(data_dict["main"].get("temp_max") - 273.15) condition = data_dict["weather"][0].get("main") icon_url = data_dict["weather"][0].get("icon") + ".png" hum = data_dict["main"].get("humidity") suns = datetime.datetime.fromtimestamp( data_dict["sys"].get("sunset")).strftime('%H:%M') sunr = datetime.datetime.fromtimestamp( data_dict["sys"].get("sunrise")).strftime('%H:%M') pres = data_dict["main"].get("pressure") wind = data_dict["wind"].get("speed") windd = data_dict["wind"].get("deg") return render_template("home.html", time=time, date=date, city_name=city_name, country_name=country_name, temp=temp, temp_min=temp_min, temp_max=temp_max, icon_url=icon_url, hum=hum, suns=suns, sunr=sunr, pres=pres, wind=wind, windd=windd)
def advertising_loopback(self, Device, AS_id, Interface, mask): device_data = getdata.get_data() hostname = device_data['Device_Details'][Device]['Hostname'] Dev = Devices.Devices() child = Dev.connect(Device) if child: clear_buffer.flushBuffer(10, child) child.sendcontrol('m') child.sendcontrol('m') child.sendcontrol('m') flag = child.expect([hostname+'>', hostname+'#', 'Router\>', 'Router\#', \ pexpect.EOF, pexpect.TIMEOUT], timeout=90) if flag in (0, 2): Dev.Login(Device, child) configs = """ configure terminal router bgp %d network %s mask %s end """ % (AS_id, Interface, mask) commands = configs.split('\n') execute.execute(child, commands) child.sendcontrol('m') if flag in (1, 3): configs = """ configure terminal router bgp %d network %s mask %s end """ % (AS_id, Interface, mask) commands = configs.split('\n') execute.execute(child, commands) child.sendcontrol('m') return True else: return False
def show_dataset_examples(show: bool, number_of_images=10): if not show: return horse_dir, human_dir, horse_dir_validation, human_dir_validation = get_data( unzipped=True) horse_names = os.listdir(horse_dir) human_names = os.listdir(human_dir) horse_pics = [ os.path.join(horse_dir, name) for name in get_random_items(horse_names, number_of_images) ] human_pics = [ os.path.join(human_dir, name) for name in get_random_items(human_names, number_of_images) ] show_images = horse_pics + human_pics print_images(show_images, "Random Training Images") # display some validation images horse_names = os.listdir(horse_dir_validation) human_names = os.listdir(human_dir_validation) horse_pics = [ os.path.join(horse_dir_validation, name) for name in get_random_items(horse_names, number_of_images) ] human_pics = [ os.path.join(human_dir_validation, name) for name in get_random_items(human_names, number_of_images) ] show_images = horse_pics + human_pics print_images(show_images, "Random Validation Images")
def checking_operabilty(Device, command): device_data = getdata.get_data() hostname = device_data['Device_Details'][Device]['Hostname'] Dev = Devices.Devices() child = Dev.connect(Device) if (child): clear_buffer.flushBuffer(10, child) child.sendcontrol('m') child.sendcontrol('m') child.sendcontrol('m') flag = child.expect([ hostname + '>', hostname + '#', 'Router\>', 'Router\#', pexpect.EOF, pexpect.TIMEOUT ], timeout=90) if flag == 0 or flag == 2: Dev.Login(Device, child) configs = """ %s """ % (command) commands = configs.split('\n') execute.execute(child, commands) child.sendcontrol('m') if flag == 1 or flag == 3: configs = """ %s """ % (command) commands = configs.split('\n') execute.execute(child, commands) child.sendcontrol('m') return True else: return False
def word_pinyin(path, out_path): ''' get_data返回的是一个字典,要获取数据就要加['data'],['0']表示第一张表,其中必须是str,不是下标 例如data = [['打字频次', '词语'], [146977.0, '提拉'], [342048.0, '流逝'], [183593.0, '周一'], [149140.0, '一课'], [141673.0, '救'], [116314.0, '随'], [96374.0, '下集']] ''' localtime = time.strftime("%Y-%m-%d", time.localtime()) out_path = out_path + '%s.txt' % localtime with open(out_path, 'w') as f: data = get_data(path)['data']['0'] data = data[1::] for x in data: # # x = ['打字频次', '词语'] pinyin = to_pinyin(x[1]) row = ('%s' + '\t' + '%s' + '\n') % (x[1], pinyin) f.write(row) f.close() print('ok')
def pingvrf_PE(Device, vrf_name, host_ip): device_data = getdata.get_data() IP_add = device_data['Device_Details'][Device]['ip_add'] Port_no = device_data['Device_Details'][Device]['port'] child = pexpect.spawn('telnet ' + IP_add + ' ' + Port_no) clear_buffer.flushBuffer(1, child) if child: child.sendcontrol('m') child.sendcontrol('m') flag = child.expect(['R*#', pexpect.EOF, pexpect.TIMEOUT], timeout=50) if flag == 0: configs = "ping vrf %s %s" % (vrf_name, host_ip) commands = configs.split('\n') execute.execute(child, commands) resp = child.before.decode('utf-8') child.sendcontrol('m') child.sendcontrol('m') regex = r'Success rate is \d+ percent \(\d\/\d\)*' if re.search(regex, resp): return True else: return False else: return False
def connect(self, Device): device_data = getdata.get_data() IP_add = device_data['Device_Details'][Device]['ip_add'] Port_no = device_data['Device_Details'][Device]['port'] Password = device_data['Device_Details'][Device]['pwd'] hostname = device_data['Device_Details'][Device]['Hostname'] child = pexpect.spawn('telnet ' + IP_add + ' ' + Port_no) if not device_data['Device_Details'][Device]['port'] == 'zebra': child.sendcontrol('m') child.sendcontrol('m') try: clear_buffer.flushBuffer(1, child) except pexpect.exceptions.EOF as exc: return False child.sendcontrol('m') child.sendcontrol('m') child.sendcontrol('m') flag = child.expect(['Router>', 'Router#', hostname+'>', hostname+'#', \ 'Password*', pexpect.EOF, pexpect.TIMEOUT], timeout=50) if flag in (0, 1, 2, 3, 4): self.Login(Device, child) if flag == 5: return False if flag == 6: self.connect(Device) return child
def Configure_mpls(self, Device, Links, mpls_label_proto, Action): device_data = getdata.get_data() hostname = device_data['Device_Details'][Device]['Hostname'] Dev = Devices.Devices() child = Dev.connect(Device) if child: clear_buffer.flushBuffer(1, child) child.sendcontrol('m') child.sendcontrol('m') child.sendcontrol('m') flag = child.expect([hostname+'>', hostname+'#', 'Router\>', 'Router\#', \ pexpect.EOF, pexpect.TIMEOUT], timeout=90) if flag in (1, 3): Dev.Login(Device, child) if Action == 'enable': if isinstance(Links, list): for Lnk in Links: interface = device_data['Link_Details'][Lnk][ Device] configs = """ configure terminal ip cef mpls label protocol %s mpls ldp router-id Loopback0 force interface %s mpls ip mpls label protocol %s exit exit """ % (mpls_label_proto, interface, mpls_label_proto) commands = configs.split('\n') execute.execute(child, commands) time.sleep(6) child.sendcontrol('m') child.sendline('exit') child.sendcontrol('m') else: if isinstance(Links, list): for Lnk in Links: interface = device_data['Link_Details'][Lnk][ Device] unconfig = """ configure terminal no mpls label protocol %s no mpls ldp router-id Loopback0 force interface %s no mpls ip no mpls label protocol %s exit exit """ % (mpls_label_proto, interface, mpls_label_proto) commands = unconfig.split('\n') execute.execute(child, commands) time.sleep(6) child.sendcontrol('m') return True else: return False
def connect_all(self, Action): device_data = getdata.get_data() devices = device_data["Device_Details"] for keys in devices.keys(): child = pexpect.spawn('telnet ' + devices[keys]['ip_add'] + ' ' + devices[keys]['port']) child.sendline('\n') child.sendcontrol('m') hostname = devices[keys]['Hostname'] clear_buffer.flushBuffer(10, child) child.sendcontrol('m') child.sendcontrol('m') child.sendcontrol('m') child.sendcontrol('m') child.sendcontrol('m') flag = (child.expect([ 'Would', 'Router', hostname + '>', hostname + '#', pexpect.EOF, pexpect.TIMEOUT ], timeout=100)) if flag == 0: time.sleep(35) #print 'Telnet connection established with device '+keys #print 'Device %s is booting' % keys child.send('no') child.sendcontrol('m') time.sleep(15) child.sendcontrol('m') flag = 1 if (flag == 1): time.sleep(35) #print "Device %s in user mode" % keys child.expect( ['Router', hostname + '#', pexpect.EOF, pexpect.TIMEOUT], timeout=40) child.sendcontrol('m') self._enable_pwd(child, keys, devices) if flag == 2 or flag == 3: #print "Hostname and password already set" self._enable_pwd(child, keys, devices) passwd = devices[keys]['pwd'] if Action == 'disable': child.sendcontrol('m') child.send('enable') child.sendcontrol('m') #child.sendcontrol('m') pwd = child.expect( ['Password', pexpect.EOF, pexpect.TIMEOUT], timeout=50) # if pwd != 0: # print "Password already unset" if pwd == 0: # print "unset the password and hostname" child.sendline(passwd) child.sendcontrol('m') unconfig = """ configure terminal no hostname %s no enable password %s exit exit """ % (hostname, devices[keys]['pwd']) commands = unconfig.split('\n') execute.execute(child, commands) child.sendcontrol('m') child.sendcontrol('m') time.sleep(10) # print "Hostname and Password unset for %s" % keys # else: # print " " # if flag == 3: #print 'Unable to connect to remote host %s:Connection refused' % keys #if flag == 4: # print 'Telnet connection established with device '+keys # print 'Timeout, no expected prompt found' return