Exemple #1
0
def ssh(connection_string, command, identity, port, rpass, rphrase,
        command_args):
    """Will execute COMMAND via ssh

    Please pass CONNECTION_STRING in the followin format:
    [username[:password]@]<host>

    COMMAND: command to execute

    COMMAND_ARGS: params, passed to COMMAND, please prepend them with "--"\n
    """
    user, password, host = parse_connection_string(connection_string)

    if rpass:
        password = getpass.getpass('Password: '******'Passphrase: ') if rphrase else None

    executor = SSHExecutor(
        host,
        port=port,
        user=user,
        password=password,
        key_path=identity,
        passphrase=passphrase,
    )

    with executor:
        res = json_repr(*executor.execute(command, command_args))

    click.echo(res)
Exemple #2
0
class TestSSHExecutor(unittest.TestCase):
    def setUp(self):
        self.executor = SSHExecutor('127.0.0.1',
                                    user='******',
                                    password='******')

    def test_ok(self):
        with self.executor:
            return_code, stdout, stderr = self.executor.execute('pwd')
        self.assertEqual(return_code, 0)
        self.assertEqual(stdout.strip(), '/home/admin')
        self.assertEqual(stderr.strip(), '')

    def test_command_not_found(self):
        with self.executor:
            return_code, stdout, stderr = self.executor.execute(
                'unknowncommand')

        self.assertEqual(return_code, 127)
        self.assertEqual(stdout.strip(), '')
        self.assertIn('not found', stderr)

    def test_command_failed(self):
        with self.executor:
            return_code, stdout, stderr = self.executor.execute('which')

        self.assertEqual(return_code, 1)
        self.assertEqual(stdout.strip(), '')
        self.assertEqual(stderr.strip(), '')
        pass

    def test_command_with_params(self):
        with self.executor:
            return_code, stdout, stderr = self.executor.execute(
                'ls', ('-a', '/etc/testing'))

        self.assertEqual(return_code, 0)
        self.assertIn('..', stdout)
        self.assertIn('requirements.txt', stdout)
        self.assertEqual(stderr.strip(), '')
        pass

    def test_command_without_connection(self):
        with self.assertRaises(ValueError):
            self.executor.execute('ls')