Skip to content

Commit 8503f01

Browse files
authored
Merge pull request #22 from makermelissa/main
Allow run_command to run as user
2 parents 5bee577 + 3ede731 commit 8503f01

File tree

2 files changed

+26
-5
lines changed

2 files changed

+26
-5
lines changed

.pylintrc

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -396,4 +396,4 @@ min-public-methods=1
396396

397397
# Exceptions that will emit a warning when being caught. Defaults to
398398
# "Exception"
399-
overgeneral-exceptions=Exception
399+
overgeneral-exceptions=builtins.Exception

adafruit_shell.py

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929
import platform
3030
import fileinput
3131
import re
32+
import pwd
3233
from datetime import datetime
3334
from clint.textui import colored, prompt
3435
import adafruit_platformdetect
@@ -65,7 +66,9 @@ def select_n(message, selections):
6566
)
6667
return prompt.options(message, options)
6768

68-
def run_command(self, cmd, suppress_message=False, return_output=False):
69+
def run_command(
70+
self, cmd, suppress_message=False, return_output=False, run_as_user=None
71+
):
6972
"""
7073
Run a shell command and show the output as it runs
7174
"""
@@ -79,13 +82,31 @@ def read_stream(output):
7982
except TypeError:
8083
return ""
8184

85+
# Allow running as a different user if we are root
86+
if self.is_root() and run_as_user is not None:
87+
pw_record = pwd.getpwnam(run_as_user)
88+
env = os.environ.copy()
89+
env["HOME"] = pw_record.pw_dir
90+
env["LOGNAME"] = run_as_user
91+
env["USER"] = pw_record.pw_name
92+
93+
def preexec():
94+
os.setgid(pw_record.pw_gid)
95+
os.setuid(pw_record.pw_uid)
96+
97+
else:
98+
env = None
99+
preexec = None
100+
82101
full_output = ""
83-
with subprocess.Popen(
102+
with subprocess.Popen( # pylint: disable=subprocess-popen-preexec-fn
84103
cmd,
85104
shell=True,
86105
stdout=subprocess.PIPE,
87106
stderr=subprocess.PIPE,
88107
universal_newlines=True,
108+
env=env,
109+
preexec_fn=preexec,
89110
) as proc:
90111
while proc.poll() is None:
91112
err = read_stream(proc.stderr)
@@ -203,9 +224,9 @@ def chdir(self, directory):
203224
# directory = self.getcwd() + "/" + directory
204225
directory = self.path(directory)
205226
if not self.exists(directory):
206-
raise ValueError("Directory does not exist")
227+
raise ValueError(f"Directory '{directory}' does not exist")
207228
if not self.isdir(directory):
208-
raise ValueError("Given location is not a directory")
229+
raise ValueError(f"The given location '{directory}' is not a directory")
209230
os.chdir(directory)
210231

211232
def pushd(self, directory):

0 commit comments

Comments
 (0)