def _iframe_config(self,config):
     config=config.split(':')
     if config[0] == 'input' :
         if len(config) == 3 :
             self._iframe_input_box(config[1],config[2])
         else:
             raise ExpectError("number of args is error ,please check.")
     elif config[0] == 'select':
         if len(config) == 2 :
             self._iframe_select(name=None,value=config[1])
         elif len(config) == 3:
             self._iframe_select(name=config[1],value=config[2])
         else:
             raise ExpectError("number of args is error ,please check.")
     elif config[0] == 'checkbox':
         if len(config) == 3 :
             self._iframe_conf_checkbox(config[1],config[2])
         else:
             raise ExpectError("number of args is error ,please check.")
     elif config[0] == 'radio':
         if len(config) == 3 :
             self._iframe_radio(config[1],config[2])
         else:
             raise ExpectError("number of args is error ,please check.")
     elif config[0] == 'submit':
         if len(config) == 2 :
             self._iframe_submit_options(config[1])
         else:
             raise ExpectError("number of args is error ,please check.")
 def _status_check(self,name,status,expect,message=None):
     if str(status) == str(expect) :
         print("status check Success , %s current status : %s,  expect status : %s"%(name,status,expect))
     else :
         if message==None :
             raise ExpectError("status check False , %s current status : %s,  expect status : %s"%(name,status,expect))
         else :
             raise ExpectError("status check False , %s current status : %s,  expect status : %s  message=%s"%(name,status,expect,message))
 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 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 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 _working_pc_version(self):
     if re.search('2003', platform.release()) or re.search(
             'xp', platform.release()):
         return 1
     elif re.search('7', platform.release()):
         return 2
     else:
         raise ExpectError("no support OS")
 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 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"%unicode(body,'utf8'))
                 print("expect get url from host:%s success, actually sucess"%host)
         else :
             print("body:\n%s"%body)
             _searchchar(searchc,body,expect,'http')
 def _tcp_server(self, ip=None, port=1000, ip_type=4):
     if int(ip_type) == 4:
         s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     else:
         s = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
     #s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
     try:
         s.bind((ip, port))
     except socket.error, err_msg:
         raise ExpectError(message="Bind local %s:%d failed(%s)." %
                           (ip, port, err_msg))
 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 tcp_server_stop(self, port=1000):
     """
     port = None, kill all listen port.
     port = num, kill the num port for listen.
     """
     print("run keyword:%s" % (sys._getframe().f_code.co_name))
     port = int(_unicode_to_utf(port))
     if port == None or str(port) == 'None':
         for port in self.tcp_s:
             self.tcp_s[port].terminate()
             self.tcp_s[port].join()
     else:
         try:
             port = int(port)
         except ValueError, msg:
             raise ExpectError(message="\"port\" is not a number.\(%s\)" %
                               msg)
         else:
 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_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_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 _features_page(self,way):
     '''
     进入到功能页面,格式 分类-模块-功能(-子功能)
     示例:
     self._features_page("策略-防护策略-入侵防护-入侵防护策略")
     self._features_page("策略-防护策略-黑名单")
     '''
     way=way.split('-')
     #self.browser.switch_to.parent_frame() #进入到iframe后回到进入前的界面
     #self.browser.switch_to_default_content() #进入到iframe后回到root界面
     print("into page %s"%str('-'.join(way)))
     self.browser.refresh()#刷新页面
     if len(way) >= 2 :
         self.browser.find_element_by_xpath(self.element._get_classification_element(way[0])).click()
         self.browser.find_element_by_xpath(self.element._get_module_element(way[1])).click()
         if len(way) == 3:
             self.browser.find_element_by_xpath(self.element._get_function_element(way[2])).click()
             if len(way) == 4:
                 self.browser.find_element_by_xpath(self.element._get_function_element(way[3])).click()
     else :
         raise ExpectError("number of args is error ,please check.")
     self.browser.switch_to_frame("Main_con")#进入到iframe Main_con
 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)
Exemplo n.º 18
0
    def waf_api(self, url, action="GET", expect=1, *args, **kwargs):
        '''
        action : PUT,DELETE,HEAD 以及 OPTIONS。
        RequestPayload : Client上传的数据。
        expectPayload : Server发送的数据。
        expect_status_code : API请求返回的状态码,默认200。 
        expect : 1 success or 0 fail,expectpayload内容不为空才有效。
        '''
        print("run keyword : {}  {}".format(sys._getframe().f_code.co_name,
                                            locals()))
        req = self.__GetAction(action.lower())
        try:
            if 'RequestPayload' in kwargs:
                r = req(url, kwargs['RequestPayload'])
            else:
                r = req(url)
            replayPayloadText = r.text
            time.sleep(5)

            if str(expect) == '1':
                if 'expectPayload' in kwargs:
                    if 'application/json' in r.headers['Content-Type']:
                        replyPayload = self.__ToDict(replayPayloadText)
                        if isinstance(kwargs['expectPayload'], str):
                            kwargs['expectPayload'] = self.__ToDict(
                                kwargs['expectPayload'])
                        if kwargs['expectPayload'] not in replyPayload['data']:
                            raise ExpectError(
                                'expectPayload eroor : expect %s, actually %s'
                                % (kwargs['expectPayload'], replayPayloadText))
                    #elif 'text' in r.headers['Content-Type'] :
                    else:
                        print("headers :", r.headers)
                        raise ExpectError('use wrong keyword.')

                if 'expect_status_code' in kwargs and int(
                        kwargs['expect_status_code']) != r.status_code:
                    raise ExpectError(
                        'status_code eroor : expect %s, actually %s' %
                        (kwargs['expect_status_code'], r.status_code))
                elif 'expect_status_code' in kwargs:
                    print("expect_status_code : {}".format(
                        kwargs['expect_status_code']))

            elif str(expect) == '0':
                if 'expectPayload' in kwargs:
                    if 'json' in r.headers['Content-Type']:
                        replyPayload = self.__ToDict(replayPayloadText)
                        if isinstance(kwargs['expectPayload'], str):
                            kwargs['expectPayload'] = self.__ToDict(
                                kwargs['expectPayload'])
                        if kwargs['expectPayload'] in replyPayload['data']:
                            raise ExpectError(
                                'expectPayload eroor : expect %s, actually %s'
                                % (kwargs['expectPayload'], replayPayloadText))
                    #elif 'text' in r.headers['Content-Type'] :
                    else:
                        raise ExpectError('use wrong keyword.')

                if 'expect_status_code' in kwargs and int(
                        kwargs['expect_status_code']) == r.status_code:
                    raise ExpectError(
                        'status_code eroor : expect %s, actually %s' %
                        (kwargs['expect_status_code'], r.status_code))
            elif expect == None or expect == "None":
                print("expect is None.")

        except:
            if expect == None:
                pass
            else:
                raise
        if port == None or str(port) == 'None':
            for port in self.tcp_s:
                self.tcp_s[port].terminate()
                self.tcp_s[port].join()
        else:
            try:
                port = int(port)
            except ValueError, msg:
                raise ExpectError(message="\"port\" is not a number.\(%s\)" %
                                  msg)
            else:
                try:
                    self.tcp_s[int(port)].terminate()
                    self.tcp_s[int(port)].join()
                except KeyError, msg:
                    raise ExpectError(message="\"port is error. \(%s\)\"" %
                                      msg)

    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:
Exemplo n.º 20
0
    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)
Exemplo n.º 21
0
    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()