def win_set_dhcp_ip(self, inter='test', searchip=None, ip_type=4, times=30): print("run keyword:%s" % (sys._getframe().f_code.co_name)) inter = _unicode_to_utf(inter) searchip = _unicode_to_utf(searchip) ip_type = _unicode_to_utf(str(ip_type)) times = _unicode_to_utf(times) msgs = [] if self._working_pc_version() == 1: cmd = 'netsh interface ip set address name="' + inter + '" source=dhcp' elif self._working_pc_version() == 2: cmd = 'netsh interface ipv4 set address name="' + str( inter) + '" source=dhcp ' print("%s" % cmd) p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) p.wait() msgs.append(p.stdout.read()) msgs.append(p.stderr.read()) p.terminate() msg = '\n'.join(msgs) print("%s" % unicode(msg, global_encoding)) self.win_show_ip(inter, searchip, ip_type, times)
def audit_drop_tables(self, host='', username=dut_user, passwd=dut_passwd): ''' clear mysql syslog tables. ''' print("run keyword:%s" % (sys._getframe().f_code.co_name)) host = _unicode_to_utf(host) username = _unicode_to_utf(username) passwd = _unicode_to_utf(passwd) tl, msgs = self._login_diagnose(host, username, passwd) tl.write("echo \"use syslog; show tables;\" | mysql\n") msg = tl.read_until('#', self.timeout) msgs.append(msg) pattern = re.compile(r"[a-z_]*_[0-9]{8}") tables_data = [] for pat in pattern.finditer(msg): tables_data.append(pat.group()) for i in tables_data: tl.write("echo \"use syslog; drop table " + i + ";\" | mysql\n") msg = tl.read_until('#', self.timeout) msgs.append(msg) tl.write("echo \"use syslog; show tables;\" | mysql\n") msg = tl.read_until('#', self.timeout) msgs.append(msg) tl.close() msgs = ' '.join(msgs) print("%s" % msgs)
def audit_drop_tables(self,host='',username=dut_user,passwd=dut_passwd): ''' clear mysql syslog tables. ''' print("run keyword:%s"%(sys._getframe().f_code.co_name)) host=_unicode_to_utf(host) username=_unicode_to_utf(username) passwd=_unicode_to_utf(passwd) tl,msgs=self._login_diagnose(host,username,passwd) tl.write("echo \"use syslog; show tables;\" | mysql\n") msg=tl.read_until('#',self.timeout) msgs.append(msg) pattern=re.compile(r"[a-z_]*_[0-9]{8}") tables_data=[] for pat in pattern.finditer(msg): tables_data.append(pat.group()) for i in tables_data: tl.write("echo \"use syslog; drop table "+i+";\" | mysql\n") msg=tl.read_until('#',self.timeout) msgs.append(msg) tl.write("echo \"use syslog; show tables;\" | mysql\n") msg=tl.read_until('#',self.timeout) msgs.append(msg) tl.close() msgs=' '.join(msgs) print("%s"%msgs)
def win_ip_del(self,inter='test',ip=None,ip_type=4): """ del ip from interface, ip_type is 4(ipv4) or 6(ipv6). eg: | Win Ip Del | inter | ip | ip_type | """ inter=_unicode_to_utf(inter) ip=_unicode_to_utf(ip) ip_type=_unicode_to_utf(str(ip_type)) print("run keyword:%s"%(sys._getframe().f_code.co_name)) msgs=[] if int(ip_type) == 4: ip_type=4 elif int(ip_type) == 6 : ip_type=6 else: raise ExpectError("ip type error") if int(ip_type) == 4: if self._working_pc_version() == 1: cmd='netsh interface ip delete address "'+str(inter)+'" addr='+ip+' gateway=all' elif self._working_pc_version() == 2: cmd='netsh interface ipv4 delete address "'+str(inter)+'" addr='+ip+' gateway=all' else: directly_route=ip.split('::')[0]+'::/64' ip=ip.split('/')[0] cmd='netsh interface ipv6 delete route '+directly_route+' "'+inter +'" && netsh interface ipv6 delete address "'+str(inter)+'" '+ip print("%s"%cmd) p=subprocess.Popen(cmd,stdin=subprocess.PIPE,stdout = subprocess.PIPE, stderr = subprocess.PIPE, shell = True) p.wait() msgs.append(p.stdout.read()) msgs.append(p.stderr.read()) p.terminate() msg='\n'.join(msgs) print("%s"%unicode(msg,global_encoding)) self.win_show_ip(inter='test',searchip=None,ip_type=ip_type)
def win_ping(self,inter='test',host=None,num=2,times=2,expect=1): print("run keyword:%s"%(sys._getframe().f_code.co_name)) inter=_unicode_to_utf(inter) host=_unicode_to_utf(host) num=_unicode_to_utf(num) times=_unicode_to_utf(times) expect=_unicode_to_utf(expect) msgs=[] stat=0 for i in range(int(times)) : tmp_msgs=[] cmd='ping '+str(host)+' -n '+str(num) print("%s"%cmd) p=subprocess.Popen(cmd,stdin=subprocess.PIPE,stdout = subprocess.PIPE, stderr = subprocess.PIPE, shell = True) p.wait() tmp_msgs.append(p.stdout.read()) tmp_msgs.append(p.stderr.read()) p.terminate() msgs.extend(tmp_msgs) reobj=re.compile('\(0% loss\)|\(0% 丢失\)') tmp_msgs=' '.join(tmp_msgs) tmp_msgs=unicode(tmp_msgs,chardet.detect(tmp_msgs)['encoding']).encode('utf-8') if reobj.search(tmp_msgs) : stat = 1 break print("%s"%unicode('\n'.join(msgs),chardet.detect('\n'.join(msgs))['encoding'])) if expect != 'None' and expect != None : if int(stat) == int(expect) : print("Expect is %s, actually %s"%('success' if int(expect) == 1 else 'fail','success' if int(expect) == 1 else 'fail')) else: raise ExpectError(message="Expect is %s, actually %s"%("Success" if int(expect) == 1 else "failed","success" if int(stat) == 1 else "failed"))
def win_gw_add(self,inter='test',gw=None,ip_type=4,metric=1): print("run keyword:%s"%(sys._getframe().f_code.co_name)) inter=_unicode_to_utf(inter) gw=_unicode_to_utf(gw) ip_type=_unicode_to_utf(str(ip_type)) metric=_unicode_to_utf(metric) msgs=[] if int(ip_type) != 4 and int(ip_type) != 6 : raise ExpectError("ip type error") if int(ip_type) == 4: if int(self._working_pc_version()) == 1: #cmd='route add 0.0.0.0 mask 0.0.0.0 '+str(gw) cmd='netsh interface ip add address "'+str(inter)+'" gateway='+str(gw)+' gwmetric='+str(metric) else: cmd='route add 0.0.0.0/0 '+str(gw)+ ' metric '+str(metric)+' if ' + self._get_inter_id(inter) else: cmd='route -6 add ::/0 '+str(gw) print("%s"%cmd) p=subprocess.Popen(cmd,stdin=subprocess.PIPE,stdout = subprocess.PIPE, stderr = subprocess.PIPE, shell = True) p.wait() msgs.append(p.stdout.read()) msgs.append(p.stderr.read()) p.terminate() msg='\n'.join(msgs) print("%s"%unicode(msg,global_encoding)) self.win_show_ip(inter='test',searchip=gw,ip_type=ip_type)
def win_set_static_ip(self,inter='test',ip=None,netmask='255.255.255.0',ip_type=4): '''if ip_type = 4 ,netmask = 255.255.255.0 like. if ip_type = 6 ,netmask = 2000:1::/64 like this. ''' print("run keyword:%s"%(sys._getframe().f_code.co_name)) inter=_unicode_to_utf(inter) ip=_unicode_to_utf(ip) netmask=_unicode_to_utf(netmask) ip_type=_unicode_to_utf(str(ip_type)) msgs=[] if str(ip_type) == '4': ip_type=4 elif str(ip_type) == '6' : ip_type=6 else: raise ExpectError("ip type error") if int(ip_type) == 4: if self._working_pc_version()==1 : cmd='netsh interface ip set address name="'+inter+'" static '+ip+' '+netmask elif self._working_pc_version()== 2 : cmd='netsh interface ipv4 set address name="'+inter+'" static '+ip+' '+netmask else: cmd='netsh interface ipv6 set address "'+inter+'" '+ip+' store=active && netsh interface ipv6 add route '+netmask+' "'+inter+'"' print("%s"%cmd) p=subprocess.Popen(cmd,stdin=subprocess.PIPE,stdout = subprocess.PIPE, stderr = subprocess.PIPE, shell = True) p.wait() msgs.append(p.stdout.read()) msgs.append(p.stderr.read()) p.terminate() msg='\n'.join(msgs) print("%s"%unicode(msg,global_encoding)) self.win_show_ip(inter='test',searchip=ip,ip_type=ip_type)
def capture_filter(self, inter='test', filter=None, count=10, timeout=10): """ Function: grab pcakets and filter eg: | Capture Filter | test | udp | count=10 | timeout=30 | Caputre pcakets from iface test, filter udp ,expect have packet from 192.168.2.1 to 172.16.0.1 . 10 pcakets or 30 second to be end. """ print("run keyword:%s" % (sys._getframe().f_code.co_name)) id = winpc_keyword() ifnet = id.win_show_ip(inter=_unicode_to_utf(inter), searchip='((\d{1,3}\.){3}\d{1,3})/\d{1,2}', ip_type=4, times=15) filter = _unicode_to_utf(filter) count = int(_unicode_to_utf(count)) self.timeout = timeout = int(_unicode_to_utf(timeout)) if filter == 'None': filter = None print("ifnet:%s" % ifnet) inter = scapy.all.conf.route.route(str(ifnet))[0] print("capture pcap inter=%s, filter=%s,count=%d,timeout=%d" % (inter, filter, count, timeout)) self.capture_t = threading.Thread(target=self._capture_filter, args=(inter, filter, count, timeout)) self.capture_t.daemon = False self.capture_t.start() print("start capture pcakets!")
def win_gw_add(self, inter='test', gw=None, ip_type=4, metric=1): print("run keyword:%s" % (sys._getframe().f_code.co_name)) inter = _unicode_to_utf(inter) gw = _unicode_to_utf(gw) ip_type = _unicode_to_utf(str(ip_type)) metric = _unicode_to_utf(metric) msgs = [] if int(ip_type) != 4 and int(ip_type) != 6: raise ExpectError("ip type error") if int(ip_type) == 4: if int(self._working_pc_version()) == 1: #cmd='route add 0.0.0.0 mask 0.0.0.0 '+str(gw) cmd = 'netsh interface ip add address "' + str( inter) + '" gateway=' + str(gw) + ' gwmetric=' + str( metric) else: cmd = 'route add 0.0.0.0/0 ' + str(gw) + ' metric ' + str( metric) + ' if ' + self._get_inter_id(inter) else: cmd = 'route -6 add ::/0 ' + str(gw) print("%s" % cmd) p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) p.wait() msgs.append(p.stdout.read()) msgs.append(p.stderr.read()) p.terminate() msg = '\n'.join(msgs) print("%s" % unicode(msg, global_encoding)) self.win_show_ip(inter='test', searchip=gw, ip_type=ip_type)
def win_gw_del(self,inter='test',gw=None,ip_type=4): """ inter : the name of interface in PC gw : gateway ip_type : type of ip is 4(ipv4) or 6(ipv6) eg: | win_gw_del | inter | gw | ip_type | """ print("run keyword:%s"%(sys._getframe().f_code.co_name)) inter=_unicode_to_utf(inter) gw=_unicode_to_utf(gw) ip_type=_unicode_to_utf(str(ip_type)) msgs=[] if int(ip_type) == 4: ip_type=4 elif int(ip_type) == 6 : ip_type=6 else: raise ExpectError("ip type error") if ip_type == 4: cmd='route delete 0.0.0.0/0' else : cmd='route -6 delete ::/0' print("%s"%cmd) p=subprocess.Popen(cmd,stdin=subprocess.PIPE,stdout = subprocess.PIPE, stderr = subprocess.PIPE, shell = True) p.wait() msgs.append(p.stdout.read()) msgs.append(p.stderr.read()) p.terminate() msg='\n'.join(msgs) print("%s"%unicode(msg,global_encoding)) self.win_show_ip(inter='test',searchip=None,ip_type=ip_type)
def tftp_file(self, host='', remote_file='', local_file='', mode=None): ''' tftp_file to get file from remote tftp server. get eg: | tftp_file | 172.16.1.100 | test1.iso | c:\\ftp\\test1.iso | get | get test1.iso freom tftp server 172.16.1.100 save local file c:\ftp\test1.iso put eg: | tftp_file | 172.16.1.100 | test1.iso | c:\\ftp\\test1.iso | put | put local file c:\ftp\test1.iso to tftp server 172.16.1.100 named test1.iso ''' print("run keyword:%s host=%s" % (sys._getframe().f_code.co_name, host)) host = _unicode_to_utf(host) remote_file = _unicode_to_utf(remote_file) local_file = _unicode_to_utf(local_file) mode = _unicode_to_utf(mode) client = tftpy.TftpClient(host, 69) if mode == None or mode == 'get' or mode == 'Get' or mode == 'None': client.download(remote_file, local_file) elif mode == 'put' or mode == 'Put': client.upload(remote_file, local_file) else: raise ExpectError("action %s error" % mode)
def sendarp(self,IP=None,count=None): '''发送arp请求报文.例 | sendarp | IP | count | ''' print("run keyword:%s"%(sys._getframe().f_code.co_name)) IP=_unicode_to_utf(IP) count=_unicode_to_utf(count) ip=self.IP_change(IP,count) self._sendarp(ip)
def sendicmp6(self,dip=None,dmac=None,sip_start=None,sip_end=None): print("run keyword:%s"%(sys._getframe().f_code.co_name)) dip=_unicode_to_utf(dip) dmac=_unicode_to_utf(dmac) sip_start=_unicode_to_utf(sip_start) sip_end=_unicode_to_utf(sip_end) isport=random.randint(1,65535) a=IPv6(dst=dip)/ICMPv6EchoRequest() send(a)
def sendudp6(self,dip=None,port=None,count=None): print("run keyword:%s"%(sys._getframe().f_code.co_name)) dip=_unicode_to_utf(dip) port=_unicode_to_utf(port) count=_unicode_to_utf(count) a=[] count=int(count) for i in range (count): isport=random.randint(1,65535) a.append(IPv6(dst=dip)/UDP(sport=isport,dport=port)) send(a)
def sendtcp6(self,dip=None,dmac=None,port=None,sip_start=None,sip_end=None): print("run keyword:%s"%(sys._getframe().f_code.co_name)) dip=_unicode_to_utf(dip) dmac=_unicode_to_utf(dmac) port=_unicode_to_utf(port) sip_start=_unicode_to_utf(sip_start) sip_end=_unicode_to_utf(sip_end) isport=random.randint(1,65535) a=IPv6(dst=dip)/UDP(sport=isport,dport=port) send(a)
def http_serv(self,ip='0.0.0.0',port=80): ''' http_cli action get: "测试!!!!!!!!"、"test"、"邪教"、"さしす" http_cli action post: "测试!!!!!!!!" ''' print("run keyword:%s"%(sys._getframe().f_code.co_name)) ip=_unicode_to_utf(ip) port=_unicode_to_utf(port) process=multiprocessing.Process(target=self._http_serv_simple,args=(ip,port,)) process.daemon=True process.start() self.serProcess.append(process) print("http server %s:%s is starting~"%(ip,str(port)))
def stmps_send_attachment(self, mailto_list=['*****@*****.**'], sub='autotest', content='autotest', att_file='e:\/mail\/abc.txt', mail_host='192.168.2.114', mail_user='******', mail_pass='******', mail_postfix='autotest.com', charset='utf-8'): '''mailto_list : send mail to user,value is a list(mor user is [email protected],[email protected] .) ; att_file : attachment path; charset : code tpye: utf-8,gb2312,and so on;''' print("run keyword:%s" % (sys._getframe().f_code.co_name)) mailto_list = _unicode_to_utf(mailto_list).split(',') #mailto_list=mailto_list.split(',') sub = _unicode_to_utf(sub) content = _unicode_to_utf(content) att_file = _unicode_to_utf(att_file) mail_host = _unicode_to_utf(mail_host) mail_user = _unicode_to_utf(mail_user) mail_pass = _unicode_to_utf(mail_pass) mail_postfix = _unicode_to_utf(mail_postfix) charset = _unicode_to_utf(charset) msg = MIMEMultipart() att = MIMEText(open(att_file, 'rb').read(), 'base64', charset) att["Content-Type"] = 'application/octet-stream' filepath, filename = os.path.split(att_file) att["Content-Disposition"] = 'attachment; filename="' + filename + '"' msg.attach(att) msgtxt = MIMEText(content, _charset=charset) msg.attach(msgtxt) me = "hello" + "<" + mail_user + "@" + mail_postfix + ">" msg['Subject'] = sub msg['From'] = me mailto_list_utf = unicode(mailto_list) mailto_list_utf = mailto_list_utf.encode('utf-8') mailto_list = mailto_list_utf.split(',') msg['To'] = to_list = ';'.join(mailto_list) print("stmps send attachment and text mail: %s,%s" % (mail_user, mail_pass)) server = smtplib.SMTP_SSL() server.connect(mail_host) server.login(mail_user, mail_pass) try: server.sendmail(me, to_list, msg.as_string()) print("send mail successed") except: print("send mail failed") server.quit()
def icmpflood(self,dip=None,dmac=None,count=None,IP=None): '''向指定的dip发送icmp报文,参数含义: dip:目的ip dmac:目的mac count:变化个数 IP:起始源ip,根据count数递增 | icmpflood | dip | dmac | count | IP | ''' print("run keyword:%s"%(sys._getframe().f_code.co_name)) dip=_unicode_to_utf(dip) dmac=_unicode_to_utf(dmac) count=_unicode_to_utf(count) IP=_unicode_to_utf(IP) ip=self.IP_change(IP,count) self._sendicmp(dmac,ip,dip)
def udp_client(self, ip=None, port=1000, ip_type=4, expect=1): """" expect = 1 is success expect = 0 is fail """ print("run keyword:%s" % (sys._getframe().f_code.co_name)) ip = _unicode_to_utf(ip) port = int(_unicode_to_utf(port)) ip_type = _unicode_to_utf(ip_type) expect = _unicode_to_utf(expect) stat = 1 if int(ip_type) == 4 or ip_type == None: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) elif int(ip_type) == 6: s = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM) else: raise ExpectError("ip_type error!") #s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) addr = (ip, port) s_msg = 'Send one udp packet!' try: s.connect(addr) s.settimeout(1.0) for i in range(2): s.sendall(s_msg) print("%s Send data:\"%s\" to %s" % (s.getsockname(), s_msg, str(addr))) r_msg = s.recv(2048) if not len(r_msg): print("%s recv no data from %s" % (str(s.getsockname()), str(addr))) else: print("%s recv data:\"%s\" from %s" % (str(s.getsockname()), r_msg, str(addr))) except (socket.error, socket.timeout) as msg: print("socket:%s" % msg) stat = 0 finally: s.close() if int(expect) == int(stat): print("Expect is %s, actually is %s" % ("Success" if int(expect) == 1 else "failed", "success" if int(stat) == 1 else "failed")) else: raise ExpectError(message="Expect is %s, actually is %s" % ("Success" if int(expect) == 1 else "failed", "success" if int(stat) == 1 else "failed"))
def win_dhcp_renew(self,inter='test',searchip=None,ip_type=4,times=30): print("run keyword:%s"%(sys._getframe().f_code.co_name)) inter=_unicode_to_utf(inter) searchip=_unicode_to_utf(searchip) ip_type=_unicode_to_utf(str(ip_type)) times=_unicode_to_utf(times) msgs=[] cmd='ipconfig /renew' print("%s"%cmd) p=subprocess.Popen(cmd,stdin=subprocess.PIPE,stdout = subprocess.PIPE, stderr = subprocess.PIPE, shell = True) p.wait() msgs.append(p.stdout.read()) msgs.append(p.stderr.read()) p.terminate() msg='\n'.join(msgs) print("%s"%unicode(msg,global_encoding)) self.win_show_ip(inter,searchip,ip_type,times)
def audit_mysql_table_clear(self,host='',table='',username=dut_user,passwd=dut_passwd): ''' table=file_transfer,app_others,email,instant_message,online_shopping,search-enine,social_network ''' host=_unicode_to_utf(host) table=_unicode_to_utf(table) username=_unicode_to_utf(username) passwd=_unicode_to_utf(passwd) print("run keyword:%s"%(sys._getframe().f_code.co_name)) tl,msgs=self._login_diagnose(host,username,passwd) table_name=self._find_current_table(tl,table,msgs) tl.write("echo \" use syslog; truncate table "+table_name+";\" | mysql\n") msg=tl.read_until('#',self.timeout) msgs.append(msg) tl.close() msgs=' '.join(msgs) print("%s"%msgs)
def tcpflood(self,dip=None,dmac=None,port=None,count=None,IP=None): '''向指定的dip和目的端口发送tcp,syn报文,源端口随机变化,参数含义: dip:目的ip dmac:目的mac port:目的端口 count:变化个数 IP:起始源ip,根据count数递增 | tcpflood | dip | dmac | port | count | IP | ''' print("run keyword:%s"%(sys._getframe().f_code.co_name)) dip=_unicode_to_utf(dip) dmac=_unicode_to_utf(dmac) port=_unicode_to_utf(port) count=_unicode_to_utf(count) IP=_unicode_to_utf(IP) ip=self.IP_change(IP,count) self._sendtcp(dmac,ip,dip,port)
def win_del_static_dns(self,inter='test',dns_ip='all'): print("run keyword:%s"%(sys._getframe().f_code.co_name)) inter=_unicode_to_utf(inter) dns_ip=_unicode_to_utf(dns_ip) msgs=[] if self._working_pc_version()==1 : cmd='netsh interface ip delete dns "'+inter+'" '+dns_ip elif self._working_pc_version()== 2 : cmd='netsh interface ipv4 delete dnsservers "'+inter+'" '+dns_ip print("%s"%cmd) p=subprocess.Popen(cmd,stdin=subprocess.PIPE,stdout = subprocess.PIPE, stderr = subprocess.PIPE, shell = True) p.wait() msgs.append(p.stdout.read()) msgs.append(p.stderr.read()) p.terminate() msg='\n'.join(msgs) print("%s"%unicode(msg,global_encoding)) self.win_show_ip(inter='test')
def win_set_dhcp_dns(self,inter='test',search_dns=None): print("run keyword:%s"%(sys._getframe().f_code.co_name)) inter=_unicode_to_utf(inter) search_dns=_unicode_to_utf(search_dns) msgs=[] if self._working_pc_version()==1 : cmd='netsh interface ip set dns name="'+inter+'" source=dhcp' elif self._working_pc_version()== 2 : cmd='netsh interface ipv4 set dnsservers name="'+inter+'" source=dhcp' print("%s"%cmd) p=subprocess.Popen(cmd,stdin=subprocess.PIPE,stdout = subprocess.PIPE, stderr = subprocess.PIPE, shell = True) p.wait() msgs.append(p.stdout.read()) msgs.append(p.stderr.read()) p.terminate() msg='\n'.join(msgs) print("%s"%unicode(msg,global_encoding)) self.win_show_ip(inter='test',searchip=search_dns)
def win_show_ip(self, inter='test', searchip=None, ip_type=4, times=15): print("run keyword:%s" % (sys._getframe().f_code.co_name)) msgs = [] inter = _unicode_to_utf(inter) searchip = _unicode_to_utf(searchip) ip_type = _unicode_to_utf(str(ip_type)) times = _unicode_to_utf(times) if int(ip_type) == 4: ip_type = 4 elif int(ip_type) == 6: ip_type = 6 else: raise ExpectError("ip type error") if int(ip_type) == 4: if self._working_pc_version() == 1: cmd = 'netsh interface ip show config "' + inter + '"' elif self._working_pc_version() == 2: cmd = 'netsh interface ipv4 show config "' + inter + '"' else: cmd = 'ipconfig' tm = 0 #cmd='ipconfig' for i in range(int(times)): try: print("%s" % cmd) p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) p.wait() msgs.append(p.stdout.read()) msgs.append(p.stderr.read()) p.terminate() msg = '\n'.join(msgs) print("%s" % unicode(msg, global_encoding)) return _searchchar(searchip, msg, expect=1, tpye='pc') except: tm += 1 time.sleep(1) if tm == int(times): raise ExpectError("search ip %s error" % searchip) else: print("search times %d, search error" % tm)
def tcp_server(self, ip=None, port=1000, ip_type=4): """ Listen local IP and port """ print("run keyword:%s" % (sys._getframe().f_code.co_name)) ip = _unicode_to_utf(ip) port = int(_unicode_to_utf(port)) ip_type = _unicode_to_utf(ip_type) if int(ip_type) != 4 or int(ip_type) != 6: p = multiprocessing.Process(target=self._tcp_server, args=( ip, port, ip_type, )) else: raise ExpectError("ip_type error") p.start() self.tcp_s[port] = p
def win_ip_add(self,inter='test',ip=None,netmask=None): print("run keyword:%s"%(sys._getframe().f_code.co_name)) inter=_unicode_to_utf(inter) ip=_unicode_to_utf(ip) netmask=_unicode_to_utf(netmask) msgs=[] if self._working_pc_version() == 1: cmd='netsh interface ip add address "'+inter+'" '+ip+' '+netmask elif self._working_pc_version() == 2: cmd='netsh interface ipv4 add address "'+inter+'" '+ip+' '+netmask print("%s"%cmd) p=subprocess.Popen(cmd,stdin=subprocess.PIPE,stdout = subprocess.PIPE, stderr = subprocess.PIPE, shell = True) p.wait() msgs.append(p.stdout.read()) msgs.append(p.stderr.read()) p.terminate() msg='\n'.join(msgs) print("%s"%unicode(msg,global_encoding)) self.win_show_ip(inter='test',searchip=ip)
def win_ping(self, inter='test', host=None, num=2, times=2, expect=1): print("run keyword:%s" % (sys._getframe().f_code.co_name)) inter = _unicode_to_utf(inter) host = _unicode_to_utf(host) num = _unicode_to_utf(num) times = _unicode_to_utf(times) expect = _unicode_to_utf(expect) msgs = [] stat = 0 for i in range(int(times)): tmp_msgs = [] cmd = 'ping ' + str(host) + ' -n ' + str(num) print("%s" % cmd) p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) p.wait() tmp_msgs.append(p.stdout.read()) tmp_msgs.append(p.stderr.read()) p.terminate() msgs.extend(tmp_msgs) reobj = re.compile('\(0% loss\)|\(0% 丢失\)') tmp_msgs = ' '.join(tmp_msgs) tmp_msgs = unicode( tmp_msgs, chardet.detect(tmp_msgs)['encoding']).encode('utf-8') if reobj.search(tmp_msgs): stat = 1 break print("%s" % unicode('\n'.join(msgs), chardet.detect('\n'.join(msgs))['encoding'])) if expect != 'None' and expect != None: if int(stat) == int(expect): print("Expect is %s, actually %s" % ('success' if int(expect) == 1 else 'fail', 'success' if int(expect) == 1 else 'fail')) else: raise ExpectError(message="Expect is %s, actually %s" % ("Success" if int(expect) == 1 else "failed", "success" if int(stat) == 1 else "failed"))
def win_ip_del(self, inter='test', ip=None, ip_type=4): """ del ip from interface, ip_type is 4(ipv4) or 6(ipv6). eg: | Win Ip Del | inter | ip | ip_type | """ inter = _unicode_to_utf(inter) ip = _unicode_to_utf(ip) ip_type = _unicode_to_utf(str(ip_type)) print("run keyword:%s" % (sys._getframe().f_code.co_name)) msgs = [] if int(ip_type) == 4: ip_type = 4 elif int(ip_type) == 6: ip_type = 6 else: raise ExpectError("ip type error") if int(ip_type) == 4: if self._working_pc_version() == 1: cmd = 'netsh interface ip delete address "' + str( inter) + '" addr=' + ip + ' gateway=all' elif self._working_pc_version() == 2: cmd = 'netsh interface ipv4 delete address "' + str( inter) + '" addr=' + ip + ' gateway=all' else: directly_route = ip.split('::')[0] + '::/64' ip = ip.split('/')[0] cmd = 'netsh interface ipv6 delete route ' + directly_route + ' "' + inter + '" && netsh interface ipv6 delete address "' + str( inter) + '" ' + ip print("%s" % cmd) p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) p.wait() msgs.append(p.stdout.read()) msgs.append(p.stderr.read()) p.terminate() msg = '\n'.join(msgs) print("%s" % unicode(msg, global_encoding)) self.win_show_ip(inter='test', searchip=None, ip_type=ip_type)
def win_clean_arp(self,inter='test',ip_type=4): print("run keyword:%s"%(sys._getframe().f_code.co_name)) inter=_unicode_to_utf(inter) ip_type=int(_unicode_to_utf(ip_type)) msgs=[] if ip_type == 4 : if self._working_pc_version()==1: cmd='netsh interface ip delete arpcache name="'+inter+'"' elif self._working_pc_version()==2: cmd='netsh interface ipv4 delete arpcache "'+inter+'"' elif ip_type == 6 : cmd='netsh interface ipv6 delete neighbors "'+inter+'"' print("%s"%cmd) p=subprocess.Popen(cmd,stdin=subprocess.PIPE,stdout = subprocess.PIPE, stderr = subprocess.PIPE, shell = True) p.wait() msgs.append(p.stdout.read()) msgs.append(p.stderr.read()) p.terminate() msg='\n'.join(msgs) print("%s"%unicode(msg,global_encoding))
def win_dhcp_renew(self, inter='test', searchip=None, ip_type=4, times=30): print("run keyword:%s" % (sys._getframe().f_code.co_name)) inter = _unicode_to_utf(inter) searchip = _unicode_to_utf(searchip) ip_type = _unicode_to_utf(str(ip_type)) times = _unicode_to_utf(times) msgs = [] cmd = 'ipconfig /renew' print("%s" % cmd) p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) p.wait() msgs.append(p.stdout.read()) msgs.append(p.stderr.read()) p.terminate() msg = '\n'.join(msgs) print("%s" % unicode(msg, global_encoding)) self.win_show_ip(inter, searchip, ip_type, times)
def capture_show(self, searchc=None, expect=1): """ Function: show capture pcakets eg: | Capture Show | 192.168.0.100 | 1 | """ print("run keyword:%s" % (sys._getframe().f_code.co_name)) searchc = _unicode_to_utf(searchc) expect = int(_unicode_to_utf(expect)) print("run keyword:%s" % (sys._getframe().f_code.co_name)) print("wait for capture pcakets!") time.sleep(int(self.timeout)) pcap = [] if self.capture_t.is_alive(): self.capture_t.terminate() self.capture_t.join() for i in self.cap: pcap.append(str(i.show)) strpcap = '\n'.join(pcap) print("%s" % strpcap) return _searchchar(searchc, strpcap, expect, tpye='pcap')
def capture_show(self,searchc=None,expect=1): """ Function: show capture pcakets eg: | Capture Show | 192.168.0.100 | 1 | """ print("run keyword:%s"%(sys._getframe().f_code.co_name)) searchc=_unicode_to_utf(searchc) expect=int(_unicode_to_utf(expect)) print("run keyword:%s"%(sys._getframe().f_code.co_name)) print("wait for capture pcakets!") time.sleep(int(self.timeout)) pcap=[] if self.capture_t.is_alive() : self.capture_t.terminate() self.capture_t.join() for i in self.cap: pcap.append(str(i.show)) strpcap='\n'.join(pcap) print("%s"%strpcap) return _searchchar(searchc,strpcap,expect,tpye='pcap')
def ftp_file(self,host='',ftp_file='test.file',port=21,user='******',passwd='',act='get',pasv=1,expect=1): '''host : ftp server IP ; ftp_file : if act = get,then ftp_file is a file on the server,if act=put then ftp_file is a file on local; port : server port ,default is 21; act : if is get ,then download,if is put,then putload; pasv : if = 1 is pasv ,or is port ''' print("run keyword:%s"%(sys._getframe().f_code.co_name)) host=_unicode_to_utf(host) ftp_file=_unicode_to_utf(ftp_file) port=int(_unicode_to_utf(port)) #port=int(port) user=_unicode_to_utf(user) passwd=_unicode_to_utf(passwd) act=_unicode_to_utf(act) pasv=_unicode_to_utf(pasv) result_stat=0 path='c:\\ftp\\' if os.path.isdir(path) is False: os.makedirs(path) f=ftplib.FTP() if pasv==1: f.set_pasv(1) try: f.connect(host,port,timeout=10) except Exception : if int(result_stat) != int(expect): f.quit() raise ExpectError("Connect error,Expect and result are not same!") f.login(user,passwd) if act=='get': print("get %s from ftp server %s"%(ftp_file,host)) localfile=ftp_file local_file_tmp=path+ftp_file p=re.compile('/') localfile=p.sub(r'\\',local_file_tmp) path,lfile=os.path.split(localfile) if os.path.isdir(path) is False: os.makedirs(path) remotefile='RETR '+ftp_file f.retrbinary(remotefile,open(localfile,'wb').write) elif act=='put': print("put %s to ftp server %s"%(ftp_file,host)) if os.path.isfile(path) is False: f.quit() raise ExpectError("put file is not exit!") else: remotefile='STOR '+ftp_file with open(path+ftp_file,'rb') as file_handler: f.storbinary(remotefile,file_handler,4096) # file_handler=open(path+ftp_file,'rb') # ftp.storbinary(remotefile,file_handler,4096) # file_handler.close() result_stat=1 if int(result_stat) != int(expect): f.quit() raise ExpectError("Expect and result are not same!") f.quit()
def win_set_static_ip(self, inter='test', ip=None, netmask='255.255.255.0', ip_type=4): '''if ip_type = 4 ,netmask = 255.255.255.0 like. if ip_type = 6 ,netmask = 2000:1::/64 like this. ''' print("run keyword:%s" % (sys._getframe().f_code.co_name)) inter = _unicode_to_utf(inter) ip = _unicode_to_utf(ip) netmask = _unicode_to_utf(netmask) ip_type = _unicode_to_utf(str(ip_type)) msgs = [] if str(ip_type) == '4': ip_type = 4 elif str(ip_type) == '6': ip_type = 6 else: raise ExpectError("ip type error") if int(ip_type) == 4: if self._working_pc_version() == 1: cmd = 'netsh interface ip set address name="' + inter + '" static ' + ip + ' ' + netmask elif self._working_pc_version() == 2: cmd = 'netsh interface ipv4 set address name="' + inter + '" static ' + ip + ' ' + netmask else: cmd = 'netsh interface ipv6 set address "' + inter + '" ' + ip + ' store=active && netsh interface ipv6 add route ' + netmask + ' "' + inter + '"' print("%s" % cmd) p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) p.wait() msgs.append(p.stdout.read()) msgs.append(p.stderr.read()) p.terminate() msg = '\n'.join(msgs) print("%s" % unicode(msg, global_encoding)) self.win_show_ip(inter='test', searchip=ip, ip_type=ip_type)
def telnet_ros_run(self,host='',commands='',expect=None,searchchar=None,username=ros_user,passwd=ros_passwd): host=_unicode_to_utf(host) commands=_unicode_to_utf(commands) expect=_unicode_to_utf(expect) searchchar=_unicode_to_utf(searchchar) username=_unicode_to_utf(username) passwd=_unicode_to_utf(passwd) print("run keyword:%s ***************** host=%s"%(sys._getframe().f_code.co_name,host)) tl=telnetlib.Telnet(host,23,10) tl.read_until("Login:"******"Password:"******"%s"%cmds) for cmd in cmds: print("cmd=%s"%cmd) tl.write(cmd+'\r\n') if 'print' in cmd : show_msg=tl.read_until('>',10) msgs.append(show_msg) else : msg=tl.read_until('>',10) msgs.append(msg) tl.write('\r\n') time.sleep(1) msgs=' '.join(msgs) print("%s"%msgs) tl.close() if 'show_msg' in locals().keys() : _searchchar(searchchar,show_msg,expect,'show') else: _searchchar(None,msgs,expect)
def win_show_ip(self,inter='test',searchip=None,ip_type=4,times=15): print("run keyword:%s"%(sys._getframe().f_code.co_name)) msgs=[] inter=_unicode_to_utf(inter) searchip=_unicode_to_utf(searchip) ip_type=_unicode_to_utf(str(ip_type)) times=_unicode_to_utf(times) if int(ip_type) == 4: ip_type=4 elif int(ip_type) == 6 : ip_type=6 else: raise ExpectError("ip type error") if int(ip_type) == 4: if self._working_pc_version() == 1: cmd='netsh interface ip show config "'+inter+'"' elif self._working_pc_version() == 2: cmd='netsh interface ipv4 show config "'+inter+'"' else: cmd='ipconfig' tm=0 #cmd='ipconfig' for i in range(int(times)): try : print("%s"%cmd) p=subprocess.Popen(cmd,stdin=subprocess.PIPE,stdout = subprocess.PIPE, stderr = subprocess.PIPE, shell = True) p.wait() msgs.append(p.stdout.read()) msgs.append(p.stderr.read()) p.terminate() msg='\n'.join(msgs) print("%s"%unicode(msg,global_encoding)) return _searchchar(searchip,msg,expect=1,tpye='pc') except : tm+=1 time.sleep(1) if tm == int(times): raise ExpectError("search ip %s error"%searchip) else: print("search times %d, search error"%tm)
def audit_mysql_search(self, host='', table='', expect=None, searchchar=None, username=dut_user, passwd=dut_passwd): ''' table=file_transfer,app_others,email,instant_message,online_shopping,search-enine,social_network ''' print("run keyword:%s" % (sys._getframe().f_code.co_name)) host = _unicode_to_utf(host) table = _unicode_to_utf(table) expect = _unicode_to_utf(expect) searchchar = _unicode_to_utf(searchchar) username = _unicode_to_utf(username) passwd = _unicode_to_utf(passwd) tl, msgs = self._login_diagnose(host, username, passwd) table_name = self._find_current_table(tl, table, msgs) tl.write("echo \"use syslog; select * from " + table_name + "; \" | mysql\n") msg = tl.read_until('#', self.timeout) msgs.append(msg) tl.close() msgs = ' '.join(msgs) print("%s" % msgs) _searchchar('ERR', msg, 0, 'sql') _searchchar(searchchar, msg, expect, 'sql')
def win_del_static_dns(self, inter='test', dns_ip='all'): print("run keyword:%s" % (sys._getframe().f_code.co_name)) inter = _unicode_to_utf(inter) dns_ip = _unicode_to_utf(dns_ip) msgs = [] if self._working_pc_version() == 1: cmd = 'netsh interface ip delete dns "' + inter + '" ' + dns_ip elif self._working_pc_version() == 2: cmd = 'netsh interface ipv4 delete dnsservers "' + inter + '" ' + dns_ip print("%s" % cmd) p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) p.wait() msgs.append(p.stdout.read()) msgs.append(p.stderr.read()) p.terminate() msg = '\n'.join(msgs) print("%s" % unicode(msg, global_encoding)) self.win_show_ip(inter='test')
def IP_change(self,IP=None,count=None): '''IP变化,变化后2位.例 | IP change | IP | count | ''' print("run keyword:%s"%(sys._getframe().f_code.co_name)) IP=_unicode_to_utf(IP) count=_unicode_to_utf(count) count=int(count) ip=[] ip_3=int(IP.split('.')[-2]) ip_4=int(IP.split('.')[-1]) ip_12='%s.%s' % (IP.split('.')[0],IP.split('.')[1]) for i in range(count): ip_4new=ip_4+i if 0<ip_4new<=254: ip.append(('%s.%s.%s') % (ip_12,ip_3,ip_4new)) else: ip_3new=ip_3+int(ip_4new/254) ip_4new=ip_4new%254 ip.append(('%s.%s.%s') % (ip_12,ip_3new,ip_4new)) return ip
def pop3s_resv(self, host='192.168.2.114', user='******', passwd='123456', delete=1): '''host: mail Ser IP; user: user; passwd: password;delete : is delete, 1 delete/0 not delete;''' print("run keyword:%s" % (sys._getframe().f_code.co_name)) host = _unicode_to_utf(host) user = _unicode_to_utf(user) passwd = _unicode_to_utf(passwd) delete = _unicode_to_utf(delete) pp = poplib.POP3_SSL(host) pp.user(user) pp.pass_(passwd) ret = pp.stat() for i in range(1, ret[0] + 1): down = pp.retr(i) if int(delete) == 1: for i in range(1, ret[0] + 1): pp.dele(i) pp.quit()
def win_ip_add(self, inter='test', ip=None, netmask=None): print("run keyword:%s" % (sys._getframe().f_code.co_name)) inter = _unicode_to_utf(inter) ip = _unicode_to_utf(ip) netmask = _unicode_to_utf(netmask) msgs = [] if self._working_pc_version() == 1: cmd = 'netsh interface ip add address "' + inter + '" ' + ip + ' ' + netmask elif self._working_pc_version() == 2: cmd = 'netsh interface ipv4 add address "' + inter + '" ' + ip + ' ' + netmask print("%s" % cmd) p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) p.wait() msgs.append(p.stdout.read()) msgs.append(p.stderr.read()) p.terminate() msg = '\n'.join(msgs) print("%s" % unicode(msg, global_encoding)) self.win_show_ip(inter='test', searchip=ip)
def tcp_client(self, ip=None, port=1000, ip_type=4, expect=1): """" expect = 1 is success expect = 0 is fail """ print("run keyword:%s" % (sys._getframe().f_code.co_name)) ip = _unicode_to_utf(ip) port = int(_unicode_to_utf(port)) ip_type = _unicode_to_utf(ip_type) expect = _unicode_to_utf(expect) stat = 0 if int(ip_type) == 4: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) elif int(ip_type) == 6: s = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) else: raise ExpectError("ip_type error") try: s.settimeout(1.0) s.connect((ip, port)) except (socket.error, socket.timeout) as e: if int(expect) == 0: print("Expect connect Failed, actually Failed") else: raise ExpectError( message="Connect Server %s:%d is failed(%s)." % (ip, port, e)) else: send_data = 'send one world!' s.sendall(send_data) recv_data = s.recv(8192) print("%s recv data:\"%s\" from %s " % (str(s.getsockname()), recv_data, str(s.getpeername()))) finally: s.close() if int(expect) == 0: raise ExpectError(message="Expect Failed,actually Success!")
def win_gw_del(self, inter='test', gw=None, ip_type=4): """ inter : the name of interface in PC gw : gateway ip_type : type of ip is 4(ipv4) or 6(ipv6) eg: | win_gw_del | inter | gw | ip_type | """ print("run keyword:%s" % (sys._getframe().f_code.co_name)) inter = _unicode_to_utf(inter) gw = _unicode_to_utf(gw) ip_type = _unicode_to_utf(str(ip_type)) msgs = [] if int(ip_type) == 4: ip_type = 4 elif int(ip_type) == 6: ip_type = 6 else: raise ExpectError("ip type error") if ip_type == 4: cmd = 'route delete 0.0.0.0/0' else: cmd = 'route -6 delete ::/0' print("%s" % cmd) p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) p.wait() msgs.append(p.stdout.read()) msgs.append(p.stderr.read()) p.terminate() msg = '\n'.join(msgs) print("%s" % unicode(msg, global_encoding)) self.win_show_ip(inter='test', searchip=None, ip_type=ip_type)
def win_clean_arp(self, inter='test', ip_type=4): print("run keyword:%s" % (sys._getframe().f_code.co_name)) inter = _unicode_to_utf(inter) ip_type = int(_unicode_to_utf(ip_type)) msgs = [] if ip_type == 4: if self._working_pc_version() == 1: cmd = 'netsh interface ip delete arpcache name="' + inter + '"' elif self._working_pc_version() == 2: cmd = 'netsh interface ipv4 delete arpcache "' + inter + '"' elif ip_type == 6: cmd = 'netsh interface ipv6 delete neighbors "' + inter + '"' print("%s" % cmd) p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) p.wait() msgs.append(p.stdout.read()) msgs.append(p.stderr.read()) p.terminate() msg = '\n'.join(msgs) print("%s" % unicode(msg, global_encoding))
def imap4s_resv(self, host='192.168.2.114', user='******', passwd='123456', delete=1): '''host: mail Ser IP; user: user; passwd: password;delete : is delete, 1 delete/0 not delete;''' print("run keyword:%s" % (sys._getframe().f_code.co_name)) host = _unicode_to_utf(host) user = _unicode_to_utf(user) passwd = _unicode_to_utf(passwd) delete = _unicode_to_utf(delete) m = imaplib.IMAP4_SSL(host) m.login(user, passwd) m.select() tpy, data = m.search(None, 'ALL') for num in data[0].split(): tpy, message = m.fetch(num, '(RFC822)') if int(delete) == 1: for num in data[0].split(): m.store(num, '+FLAGS', '\\Deleted') m.expunge() m.close() m.logout()
def tftp_file(self,host='',remote_file='',local_file='',mode=None): ''' tftp_file to get file from remote tftp server. get eg: | tftp_file | 172.16.1.100 | test1.iso | c:\\ftp\\test1.iso | get | get test1.iso freom tftp server 172.16.1.100 save local file c:\ftp\test1.iso put eg: | tftp_file | 172.16.1.100 | test1.iso | c:\\ftp\\test1.iso | put | put local file c:\ftp\test1.iso to tftp server 172.16.1.100 named test1.iso ''' print("run keyword:%s host=%s"%(sys._getframe().f_code.co_name,host)) host=_unicode_to_utf(host) remote_file=_unicode_to_utf(remote_file) local_file=_unicode_to_utf(local_file) mode=_unicode_to_utf(mode) client=tftpy.TftpClient(host,69) if mode == None or mode == 'get' or mode == 'Get' or mode == 'None' : client.download(remote_file,local_file) elif mode=='put' or mode=='Put' : client.upload(remote_file,local_file) else: raise ExpectError("action %s error"%mode)
def capture_filter(self,inter='test',filter=None,count=10,timeout=10): """ Function: grab pcakets and filter eg: | Capture Filter | test | udp | count=10 | timeout=30 | Caputre pcakets from iface test, filter udp ,expect have packet from 192.168.2.1 to 172.16.0.1 . 10 pcakets or 30 second to be end. """ print("run keyword:%s"%(sys._getframe().f_code.co_name)) id=winpc_keyword() ifnet=id.win_show_ip(inter=_unicode_to_utf(inter),searchip='((\d{1,3}\.){3}\d{1,3})/\d{1,2}',ip_type=4,times=15) filter=_unicode_to_utf(filter) count=int(_unicode_to_utf(count)) self.timeout=timeout=int(_unicode_to_utf(timeout)) if filter == 'None' : filter = None print("ifnet:%s"%ifnet) inter=scapy.all.conf.route.route(str(ifnet))[0] print("capture pcap inter=%s, filter=%s,count=%d,timeout=%d"%(inter,filter,count,timeout)) self.capture_t=threading.Thread(target=self._capture_filter,args=(inter,filter,count,timeout)) self.capture_t.daemon=False self.capture_t.start() print("start capture pcakets!")
def http_cli(self,host='',port=None,url='/',act='GET',expect=1,searchc=None): ''' ''' host=_unicode_to_utf(host) port=_unicode_to_utf(port) if (not port) or port == "None" or port.isspace(): port=None url=_unicode_to_utf(url) act=_unicode_to_utf(act) expect=_unicode_to_utf(expect) searchc=_unicode_to_utf(searchc) print("run keyword:%s"%(sys._getframe().f_code.co_name)) sendheader={"Accept-Encoding":"gzip, deflate, sdch",\ "Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",\ #"Content-Length":"100",\ "Connection":"keep-alive",\ "Accept-Language":"zh-CN,zh;q=0.8",\ "User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.134 Safari/537.36"} try: conn=httplib.HTTPConnection(host=host,port=port)#,timeout=10) conn.request(act,url,'',sendheader) msgs=conn.getresponse() body=msgs.read() conn.close() except: if expect == 0 or expect == '0': if searchc ==None or str(searchc) == 'None' or searchc == '': print("expect get url from host:%s fail, actually fail"%host) else : raise ExpectError("expect get url from host:%s ,connect fail"%host) else : raise ExpectError("get url from host:%s error!"%host) else: if searchc ==None or str(searchc) == 'None' or searchc == '' : if expect == 0 : raise ExpectError("expect get url from host:%s fail, actually success"%host) else : print("body:\n%s"%body) print("expect get url from host:%s success, actually sucess"%host) else : print("body:\n%s"%body) _searchchar(searchc,body,expect,'http')
def telnet_run(self,host='',commands='',expect=None,searchchar=None,timeout=None,username=dut_user,passwd=dut_passwd): """ telnet a dut and exec command,command will split by ';'. searchchar is the expect string,when expect=1,the result should contain the searchchar eg: | telnet_run | 192.168.2.132 | con t;in ge3/0;no ip add;show inter ge3/0 | 1 | search | admin | admin | when an error happend in cmd,such as '%unknown command',the program will drop an error if have show command in commands ,search result of show command;else search command have error or not """ host=_unicode_to_utf(host) commands=_unicode_to_utf(commands) expect=_unicode_to_utf(expect) searchchar=_unicode_to_utf(searchchar) timeout=_unicode_to_utf(timeout) username=_unicode_to_utf(username) passwd=_unicode_to_utf(passwd) cmds=['enable'] cmds+=commands.split(';') msgs=[] print("run keyword:%s ***************** host=%s"%(sys._getframe().f_code.co_name,host)) tl=telnetlib.Telnet(host,23,10) tl.read_until("Username:"******"Password:"******"%s"%show_msg) #msgs.append(show_msg) return _searchchar(searchchar,show_msg,expect,'show') except ExpectError as e : if i+1 == int(timeout): #msgs=' '.join(msgs) #print("%s"%msgs) raise ExpectError("search times %d error :%s"%(int(timeout),e)) else: print("search times %d error :%s"%(i,e)) time.sleep(1) else: tl.write('%s\n' % cmd) show_msg=tl.read_until('#') msgs.append(show_msg) try: print("%s"%show_msg) return _searchchar(searchchar,show_msg,expect,'show') except ExpectError as e: print("%s"%' '.join(msgs)) raise ExpectError("%s"%e) else : tl.write('%s\n' % cmd) msg=tl.read_until('#') msgs.append(msg) msgs=' '.join(msgs) print("%s"%msgs) tl.close() #_searchchar(None,msgs,expect) if 'show_msg' not in locals().keys() : _searchchar(None,msgs,expect)