Skip to content

Commit af70581

Browse files
committed
SshConnection: Implement tracking of connected_as_root status
Improve the detection of being `connected_as_root` from comparing the username to checking the actual id of the user and export this as a property for the connection.
1 parent 85fd421 commit af70581

File tree

1 file changed

+15
-2
lines changed

1 file changed

+15
-2
lines changed

devlib/utils/ssh.py

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,18 @@ class SshConnection(object):
158158
def name(self):
159159
return self.host
160160

161+
@property
162+
def connected_as_root(self):
163+
if self._connected_as_root is None:
164+
# Execute directly to prevent deadlocking of connection
165+
result = self._execute_and_wait_for_prompt('id', as_root=False)
166+
self._connected_as_root = 'uid=0(' in result
167+
return self._connected_as_root
168+
169+
@connected_as_root.setter
170+
def connected_as_root(self, state):
171+
self._connected_as_root = state
172+
161173
# pylint: disable=unused-argument,super-init-not-called
162174
def __init__(self,
163175
host,
@@ -172,6 +184,7 @@ def __init__(self,
172184
platform=None,
173185
sudo_cmd="sudo -- sh -c {}"
174186
):
187+
self._connected_as_root = None
175188
self.host = host
176189
self.username = username
177190
self.password = password
@@ -232,7 +245,7 @@ def background(self, command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, as
232245
try:
233246
port_string = '-p {}'.format(self.port) if self.port else ''
234247
keyfile_string = '-i {}'.format(self.keyfile) if self.keyfile else ''
235-
if as_root:
248+
if as_root and not self.connected_as_root:
236249
command = self.sudo_cmd.format(command)
237250
command = '{} {} {} {}@{} {}'.format(ssh, keyfile_string, port_string, self.username, self.host, command)
238251
logger.debug(command)
@@ -261,7 +274,7 @@ def cancel_running_command(self):
261274

262275
def _execute_and_wait_for_prompt(self, command, timeout=None, as_root=False, strip_colors=True, log=True):
263276
self.conn.prompt(0.1) # clear an existing prompt if there is one.
264-
if self.username == 'root':
277+
if as_root and self.connected_as_root:
265278
# As we're already root, there is no need to use sudo.
266279
as_root = False
267280
if as_root:

0 commit comments

Comments
 (0)