Пример #1
0
def sendPassword(target):
    
    if target.password is None:
        raise MissingDeviceParameter(target, '%s password undefined' % target.name)
    
    log.debug("[%s] sending password [%s] ..." % (target.name, target.password))
    target.send_line(target.password)
Пример #2
0
    def testFakeOk(self):
        log.debug("testFakeOk ...")
        h = device("telnet://%s:%s@%s:%d" % ("username", "secret", "localhost", TELNET_PORT))

        h.maxWait = 2
        out = h("id")
        print("--> %s" % out)
        self.assertRegex(out, "uid=[0-9]+\(pyco\).*")
Пример #3
0
    def testSimpleCommand(self):
        log.debug("starting testSimpleCommand ...")
        target = device('telnet://%s:%s@%s:%d' %
                        ('kenobi', 'secret', 'localhost', TELNET_PORT))

        target.maxWait = 2
        out = target('id')
        target.close()
        self.assertRegex(out, 'uid=[0-9]+\(pyco\).*')
Пример #4
0
 def db_exists(self):
     import os.path
     if hasattr(pyco, 'pyco_home'):
         db_file = '%s/%s' % (pyco.pyco_home, DEVICE_REPO)
     else:
         db_file = '/tmp/%s' % DEVICE_REPO
     try:
         if not os.path.isfile(db_file):
             log.debug('creating cache [%s] ...' % db_file)
             self.createDB('sqlite://%s' % db_file)
     except Exception as e:
         log.error('fatal error: %s' % e)
Пример #5
0
def loginSuccessfull(device):
    '''
    The checkpoint loginSuccessfull has 3 exit point:
     * return True if the state is 'USER_PROMPT'
     * raise the ConnectionTimedOut exception if the current event is timeout
     * return False otherwise
    '''
    log.debug("[%s] loginSuccessfull: current_state [%s]" % (device.name, device.state))
    if device.state == 'USER_PROMPT':
        device.loggedin = True
        return True
#    if device.currentEvent.name == 'timeout':
#        raise ConnectionTimedOut(device)
    return False
Пример #6
0
    def testMulti(self):
        log.debug("testMulti ...")
        setface("ciscoios")

        h = device('telnet://%s:%s@%s:%d/ciscoios' %
                   ('obi-wan-kenobi', 'secret', 'localhost', TELNET_PORT))
        h.maxWait = 2

        #p = Client()[:]

        hosts = [h] * 10

        with Pool(5) as p:
            results = p.map(command, hosts)
            self.assertEqual(len(results), 10, "expected 10 command outputs")
            self.assertNotIn(None, results, "some commands failed unexpectely")
Пример #7
0
 def testMulti(self):
     log.debug("testMulti ...")
     setface("ciscoios")
     
     h = device('telnet://%s:%s@%s:%d/ciscoios' % 
                ('obi-wan-kenobi', 'secret', 'localhost',TELNET_PORT))
     h.maxWait = 2
     
     #p = Client()[:]
     
     hosts = [h] * 10
     
     with Pool(5) as p:
         results = p.map(command, hosts)
         self.assertEqual(len(results), 10, "expected 10 command outputs")
         self.assertNotIn(None, results, "some commands failed unexpectely")
Пример #8
0
def setCliPrompt(target):
    '''
    setCliPrompt may be used when the device cli supports the PS1 command for setting the prompt.
    For example the Unix family satisfies such requirement.  
    '''
    uprompt = '_%s_pyco_> ' % target.name
    log.debug('[%s]: setting prompt to [%s]' % (target.name, uprompt))
    
    target.clear_buffer()
    
    target.send_line("PS1='%s'" % uprompt)
    
    # add the prompt without discovering it
    log.debug('[%s] matching prompt with pattern [%s]' % (target.state, uprompt))
    target.prompt[target.state] = Prompt(uprompt, tentative=False)
    target.add_expect_pattern('prompt-match', uprompt, target.state)
Пример #9
0
def loginSuccessfull(device):
    '''
    The checkpoint loginSuccessfull has 3 exit point:
     * return True if the state is 'USER_PROMPT'
     * raise the ConnectionTimedOut exception if the current event is timeout
     * return False otherwise
    '''
    log.debug("[%s] loginSuccessfull: current_state [%s]" %
              (device.name, device.state))
    if device.state == 'USER_PROMPT':
        device.loggedin = True
        return True


#    if device.currentEvent.name == 'timeout':
#        raise ConnectionTimedOut(device)
    return False
Пример #10
0
    def connect(self, position):
        """
        Connect to the device in the hops position index
        """
        prevPos = position - 1
        if prevPos < 0:
            prevDevice = SOURCE_HOST
        else:
            prevDevice = self.hops[prevPos]

        target = self.hops[position]

        log.debug("[%s] prev hop device: [%s]" %
                  (target.name, prevDevice.name))
        if not prevDevice.is_connected():
            log.debug("previous hop %s is not connected, activating ..." %
                      prevDevice.name)

            # backward propagate the session
            prevDevice.esession = target.esession
            self.connect(prevPos)

        cmd = target.connect_command(prevDevice)

        # in memory log
        #self.logfile = StringIO.StringIO()

        #logfile = file(pyco.config.expectLogfile, "w")

        log.debug("connecting using %s" % cmd)

        self.currentHop = target

        if hasattr(self, 'pipe'):
            self.send_line(cmd)
        else:
            # TODO: close the spawnued session
            # send the connect string to pexpect
            log.debug("[%s]: spawning a new [%s] session ..." % (target, cmd))
            self.pipe = spawnu(cmd, logfile=self.logfile)
        self.processResponse(target, loginSuccessfull)
Пример #11
0
    def connect(self, position):
        """
        Connect to the device in the hops position index
        """
        prevPos = position - 1
        if prevPos < 0:
            prevDevice = SOURCE_HOST
        else:
            prevDevice = self.hops[prevPos]

        target = self.hops[position]
       
        log.debug("[%s] prev hop device: [%s]" % (target.name, prevDevice.name))
        if not prevDevice.is_connected():
            log.debug("previous hop %s is not connected, activating ..." % prevDevice.name)
            
            # backward propagate the session
            prevDevice.esession = target.esession
            self.connect(prevPos)
        
            
        cmd = target.connect_command(prevDevice)
        
        # in memory log
        #self.logfile = StringIO.StringIO()
        
        #logfile = file(pyco.config.expectLogfile, "w")

        log.debug("connecting using %s" % cmd)
        
        self.currentHop = target
        
        if hasattr(self, 'pipe'):
            self.send_line(cmd)
        else:
            # TODO: close the spawnued session
            # send the connect string to pexpect
            log.debug("[%s]: spawning a new [%s] session ..." % (target, cmd)) 
            self.pipe = spawnu(cmd, logfile=self.logfile)
        self.processResponse(target, loginSuccessfull)
Пример #12
0
def responder(mock, responses, patterns, maxTime):

    log.debug('entering MOCK responder')
    print(patterns)

    #return the index relative to event_name
    response = responses.pop(0)
    log.debug('current response [%s]' % (response))

    idx = 0
    toBeMatched = True
    while toBeMatched and idx < len(patterns):

        search = '(.*)(%s)' % patterns[idx]
        log.debug("checking [%d] regexp: [%s]" % (idx, search))
        if patterns[idx] == TIMEOUT:

            toBeMatched = False
            mock.before = response
            mock.after = TIMEOUT

            break
        match = re.match(search, response, re.DOTALL)
        if match:
            toBeMatched = False
            mock.before = match.group(1)
            mock.after = match.group(2)
            break
        idx += 1

    if idx < len(patterns):
        log.debug('returning index [%d]' % idx)
        return idx
    else:
        mock.before = response
        mock.after = TIMEOUT
        raise TIMEOUT('wait time exceeded')
Пример #13
0
def responder(mock, responses, patterns, maxTime):
    
    log.debug('entering MOCK responder')
    print(patterns)

    #return the index relative to event_name
    response = responses.pop(0)
    log.debug('current response [%s]' % (response))
    
    idx = 0
    toBeMatched = True
    while toBeMatched and idx < len(patterns):
        
        search = '(.*)(%s)' % patterns[idx]
        log.debug("checking [%d] regexp: [%s]" % (idx, search))
        if patterns[idx] == TIMEOUT:
            
            toBeMatched = False
            mock.before = response
            mock.after  = TIMEOUT

            break
        match = re.match(search, response, re.DOTALL)
        if match:
            toBeMatched = False
            mock.before = match.group(1)
            mock.after  = match.group(2) 
            break
        idx+=1
    
    if idx < len(patterns):
        log.debug('returning index [%d]' % idx)
        return idx
    else:
        mock.before = response
        mock.after = TIMEOUT
        raise TIMEOUT('wait time exceeded')
Пример #14
0
    def testWrongPassword(self):
        log.debug("testWrongPassword ...")
        h = device("telnet://%s:%s@%s:%d" % ("username", "wrong_pwd", "localhost", TELNET_PORT))

        self.assertRaises(PermissionDenied, h, "id")
Пример #15
0
 def testWrongPassword(self):
     log.debug("testWrongPassword ...")
     target = device('telnet://%s:%s@%s:%d' %
                     ('kenobi', 'wrong_pwd', 'localhost', TELNET_PORT))
     target.close()
     self.assertRaises(PermissionDenied, target, 'id')
Пример #16
0
def permissionDenied(target):
    log.debug("[%s]: raising permissionDenied exception" % target.name)
    raise PermissionDenied(target)
Пример #17
0
 def testWrongUsername(self):
     log.debug("testWrongUsername ...")
     target = device('telnet://%s:%s@%s:%d' %
                     ('fake_username', 'secret', 'localhost', TELNET_PORT))
     target.close()
     self.assertRaises(PermissionDenied, target, 'id')
Пример #18
0
def connectionRefused(target):
    log.debug("[%s] connectionRefused: [%s]" % (target.name, target.interaction_log()))
    raise ConnectionRefused(target)
Пример #19
0
 def testConnectionRefused(self):
     log.debug("testConnectionRefused ...")
     target = device('telnet://%s:%s@%s:%d' %
                     ('fake_username', 'secret', 'localhost', 9999))
     target.close()
     self.assertRaises(ConnectionRefused, target, 'id')
Пример #20
0
 def send_line(self, command):
     """
     Send a command string to the device actually connected
     """
     log.debug("sending line [%s] using session [%s]" % (command, self))
     self.pipe.sendline(command)
Пример #21
0
    def patternMatch(self, target, checkPoint, patternsExt, maxWaitTime):

        target.currentEvent = Event('do-nothing-event')
        log.debug("entering patternMatch, checkpoint is [%s]" % (checkPoint))
        log.debug("exactPatternMatch [%s]" % target.exactPatternMatch)

        response = ''
        while not (checkPoint(target) or target.currentEvent.isTimeout()):

            patterns = target.patterns(target.state) + patternsExt
            # expect and match
            try:
                log.debug("[%s] matching [%s]" % (target.state, patterns))
                #log.debug("PRE exp before: [%s] - after: [%s]" % (self.pipe.before, self.pipe.after))
                if target.exactPatternMatch:
                    index = self.pipe.expect_exact(patterns, maxWaitTime)
                else:
                    index = self.pipe.expect(patterns, maxWaitTime)

                try:
                    target.currentEvent = Event(
                        target.get_event(patterns[index]))
                except Exception as e:
                    if patterns[index] == TIMEOUT:
                        log.debug("[%s]: exception timeout triggered" %
                                  target.name)
                        target.currentEvent = Event('timeout',
                                                    propagateToFsm=True)
                    else:
                        log.error(
                            "[%s]: event not registered for pattern: [%s]" %
                            (target.name, patterns[index]))
                        raise

                log.debug("matched [%s] pattern [%s] --> [%s]" %
                          (index, patterns[index], target.currentEvent.name))
                log.debug("before: [%s] - after: [%s]" %
                          (self.pipe.before, self.pipe.after))
            except EOF:
                log.debug("[%s] connection unexpectedly closed (%s)" %
                          (target.name, self.pipe.before))
                target.currentEvent = Event('eof')
            except TIMEOUT:
                log.debug("[%s] connection timed out, unmatched output: [%s]" %
                          (target.name, self.pipe.before))
                target.currentEvent = Event('timeout')

            #log.debug("detected event [%s]" % target.currentEvent)
            if target.has_event_handlers(target.currentEvent):
                log.debug("[%s] got [%s] event; invoking handlers: [%s]" %
                          (target.name, target.currentEvent.name,
                           target.get_event_handlers(target.currentEvent)))
                for eh in target.get_event_handlers(target.currentEvent):
                    eh(target)

            stateChanged = target.process(target.currentEvent)
            response += self.pipe.before
            if isinstance(self.pipe.after,
                          str) and not target.currentEvent.isPromptMatch():
                response += self.pipe.after

        return response
Пример #22
0
 def send_line(self, command):
     """
     Send a command string to the device actually connected
     """
     log.debug("sending line [%s] using session [%s]" % (command, self))
     self.pipe.sendline(command)
Пример #23
0
    def patternMatch(self, target, checkPoint, patternsExt, maxWaitTime):
        
        target.currentEvent = Event('do-nothing-event')
        log.debug("entering patternMatch, checkpoint is [%s]" % (checkPoint))
        log.debug("exactPatternMatch [%s]" % target.exactPatternMatch)
        
        response = ''        
        while not (checkPoint (target) or target.currentEvent.isTimeout()):
            
            patterns = target.patterns(target.state) + patternsExt
            # expect and match 
            try:
                log.debug("[%s] matching [%s]" % (target.state, patterns))
                #log.debug("PRE exp before: [%s] - after: [%s]" % (self.pipe.before, self.pipe.after))
                if target.exactPatternMatch:
                    index = self.pipe.expect_exact(patterns, maxWaitTime)
                else:
                    index = self.pipe.expect(patterns, maxWaitTime)
               
                try:    
                    target.currentEvent = Event(target.get_event(patterns[index]))
                except Exception as e:
                    if patterns[index] == TIMEOUT:
                        log.debug("[%s]: exception timeout triggered" % target.name)
                        target.currentEvent = Event('timeout', propagateToFsm = True)
                    else:
                        log.error("[%s]: event not registered for pattern: [%s]" % (target.name, patterns[index]))
                        raise
                        
                log.debug("matched [%s] pattern [%s] --> [%s]" % (index, patterns[index], target.currentEvent.name))
                log.debug("before: [%s] - after: [%s]" % (self.pipe.before, self.pipe.after))
            except EOF:
                log.debug("[%s] connection unexpectedly closed (%s)" % (target.name, self.pipe.before))
                target.currentEvent = Event('eof')
            except TIMEOUT:
                log.debug("[%s] connection timed out, unmatched output: [%s]" % (target.name, self.pipe.before))
                target.currentEvent = Event('timeout')

            #log.debug("detected event [%s]" % target.currentEvent)
            if target.has_event_handlers(target.currentEvent):
                log.debug("[%s] got [%s] event; invoking handlers: [%s]" % (target.name, target.currentEvent.name, target.get_event_handlers(target.currentEvent)))
                for eh in target.get_event_handlers(target.currentEvent):
                    eh(target)
           
            stateChanged = target.process(target.currentEvent)
            response += self.pipe.before
            if isinstance(self.pipe.after, str) and not target.currentEvent.isPromptMatch():
                response += self.pipe.after

        return response
Пример #24
0
def send(target, command):
    log.debug("sending string [%s] ..." % command)
    target.send_line(command)
Пример #25
0
def sendUsername(target):
    if target.username is None:
        raise MissingDeviceParameter(target, '%s username undefined' % target.name)

    log.debug("sending username  [%s] ..." % target.username)
    target.send_line(target.username)
Пример #26
0
 def setUpClass(cls):
     log.debug("setting face to linux")
     setface("linux")