From 49432f44abf3439e8f7b3000d7e041c93c9e61b7 Mon Sep 17 00:00:00 2001 From: Victor Moene Date: Fri, 20 Dec 2024 11:44:37 +0100 Subject: [PATCH] Added sudo skipping when UID is zero Ticket: CFE-4464 Signed-off-by: Victor Moene --- cf_remote/ssh.py | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/cf_remote/ssh.py b/cf_remote/ssh.py index 8b9a047..6e60360 100644 --- a/cf_remote/ssh.py +++ b/cf_remote/ssh.py @@ -18,6 +18,7 @@ class LocalConnection: def __init__(self): self.ssh_user = pwd.getpwuid(os.getuid()).pw_name + self.needs_sudo = self.run("echo $UID", hide=True).stdout.strip() != "0" def run(self, command, hide=False): # to maintain Python 3.5/3.6 compatability the following are used: @@ -62,6 +63,8 @@ def __init__(self, host, user, connect_kwargs=None): control_master_args ) # stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + self.needs_sudo = self.run("echo $UID", hide=True).stdout.strip() != "0" + def __del__(self): # If we have an SSH Control Master running, signal it to terminate. if ( @@ -198,9 +201,12 @@ def ssh_sudo(connection, cmd, errors=False): assert connection log.debug("Running(sudo) over SSH: '%s'" % cmd) - escaped = cmd.replace('"', r"\"") - sudo_cmd = 'sudo bash -c "%s"' % escaped - result = connection.run(sudo_cmd, hide=True) + if connection.needs_sudo: + escaped = cmd.replace('"', r"\"") + sudo_cmd = 'sudo bash -c "%s"' % escaped + result = connection.run(sudo_cmd, hide=True) + else: + result = connection.run(cmd, hide=True) if result.retcode == 0: output = result.stdout.strip("\n") log.debug("'%s' -> '%s'" % (cmd, output))