From af46d9f6915c0acd7ec3cb568a5e6747f04376ad Mon Sep 17 00:00:00 2001 From: Thibaud CASTAING Date: Fri, 14 Jul 2017 16:24:31 -0400 Subject: [PATCH] fix run of shell builtins commands when impersonating another user --- jumpssh/session.py | 3 ++- tests/test_session.py | 12 ++++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/jumpssh/session.py b/jumpssh/session.py index bb3f5cf..f10e073 100644 --- a/jumpssh/session.py +++ b/jumpssh/session.py @@ -237,7 +237,8 @@ def run_cmd( my_cmd = cmd if username: user = username - my_cmd = 'sudo -u %s %s' % (user, cmd) + # need to run full command with shell to support shell builtins commands (source, ...) + my_cmd = 'sudo su - %s -c "%s"' % (user, cmd.replace('"', '\\"')) if not silent: logger.debug("Running command '%s' on '%s' as %s..." % (cmd, self.host, user)) diff --git a/tests/test_session.py b/tests/test_session.py index fd7eea8..8aaeb2b 100644 --- a/tests/test_session.py +++ b/tests/test_session.py @@ -156,9 +156,21 @@ def test_run_cmd(docker_env, capfd): out, err = capfd.readouterr() assert len(out) > 0 + +def test_run_cmd_sudo(docker_env): + gateway_ip, gateway_port = docker_env.get_host_ip_port('gateway') + + gateway_session = SSHSession(host=gateway_ip, port=gateway_port, + username='user1', password='password1').open() + # run command as user2 assert gateway_session.run_cmd('whoami', username='user2')[1].strip() == 'user2' + # run bash builtins commands with sudo (here command 'source') + gateway_session.file(remote_path='/home/user2/ssh_setenv', use_sudo=True, owner='user2', + content='MY_VAR=variable_set') + gateway_session.run_cmd('source /home/user2/ssh_setenv', username='user2') + def get_cmd_output(docker_env): gateway_ip, gateway_port = docker_env.get_host_ip_port('gateway')