def login(self, server, username, password='', original_prompt=r'[#$]', login_timeout=10, auto_prompt_reset=True, sync_multiplier=1, port=23): cmd = 'telnet -l {} {} {}'.format(username, server, port) spawn._spawn(self, cmd) # pylint: disable=protected-access try: i = self.expect('(?i)(?:password)', timeout=login_timeout) if i == 0: self.sendline(password) i = self.expect([original_prompt, 'Login incorrect'], timeout=login_timeout) if i: raise pxssh.ExceptionPxssh('could not log in: password was incorrect') except TIMEOUT: if not password: # There was no password prompt before TIMEOUT, and we didn't # have a password to enter. Assume everything is OK. pass else: raise pxssh.ExceptionPxssh('could not log in: did not see a password prompt') if not self.sync_original_prompt(sync_multiplier): self.close() raise pxssh.ExceptionPxssh('could not synchronize with original prompt') if auto_prompt_reset: if not self.set_unique_prompt(): self.close() message = 'could not set shell prompt (recieved: {}, expected: {}).' raise pxssh.ExceptionPxssh(message.format(self.before, self.PROMPT)) return True
def login(self, host, auto_prompt_reset=True): # pylint: disable=arguments-differ """ Radically simplified login without the 'New certificate -- always accept it.' stuff.""" self._original_host = host spawn._spawn(self, 'ssh', args=[host]) # pylint: disable=protected-access if not self.sync_original_prompt(): self.close() raise pxssh.ExceptionPxssh('could not synchronize with original prompt') # We appear to be in. # Set shell prompt to something unique. if auto_prompt_reset: if not self.set_unique_prompt(): self.close() raise pxssh.ExceptionPxssh('could not set shell prompt') return True
def test_run_command_exception_pxssh(self): """Testing exception in run_command.""" from pexpect import pxssh self.connection._ssh = mock.Mock() self.connection._ssh.sendline = mock.Mock() self.connection._ssh.sendline.side_effect = pxssh.ExceptionPxssh( 'except') self.connection.run_command('test') self.assertFalse(self.connection._connected) self.assertIsNone(self.connection._ssh)
def test_pxssh_login(c, mocker): mock_pxssh = mocker.patch.object(pxssh, "pxssh", return_value=mocker.Mock("pxssh")) mock_pxssh.return_value.login = mocker.Mock("login") pxssh_login(c, "user", "password") mock_pxssh.return_value.login.assert_called_with( socket.gethostname(), "user", "password" ) mocker.patch("sys.exit") mocker.patch("time.sleep") mock_pxssh = mocker.patch.object( pxssh, "pxssh", side_effect=pxssh.ExceptionPxssh("ERROR") ) mock_error = mocker.patch("roast.ssh.log.error") pxssh_login(c, "user", "password") mock_error.assert_called_with( f"error: Failed to establish ssh connection with {socket.gethostname()}!" )