Skip to content

Commit

Permalink
Merge pull request #22 from makermelissa/main
Browse files Browse the repository at this point in the history
Allow run_command to run as user
  • Loading branch information
makermelissa committed Sep 14, 2023
2 parents 5bee577 + 3ede731 commit 8503f01
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 5 deletions.
2 changes: 1 addition & 1 deletion .pylintrc
Original file line number Diff line number Diff line change
Expand Up @@ -396,4 +396,4 @@ min-public-methods=1

# Exceptions that will emit a warning when being caught. Defaults to
# "Exception"
overgeneral-exceptions=Exception
overgeneral-exceptions=builtins.Exception
29 changes: 25 additions & 4 deletions adafruit_shell.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
import platform
import fileinput
import re
import pwd
from datetime import datetime
from clint.textui import colored, prompt
import adafruit_platformdetect
Expand Down Expand Up @@ -65,7 +66,9 @@ def select_n(message, selections):
)
return prompt.options(message, options)

def run_command(self, cmd, suppress_message=False, return_output=False):
def run_command(
self, cmd, suppress_message=False, return_output=False, run_as_user=None
):
"""
Run a shell command and show the output as it runs
"""
Expand All @@ -79,13 +82,31 @@ def read_stream(output):
except TypeError:
return ""

# Allow running as a different user if we are root
if self.is_root() and run_as_user is not None:
pw_record = pwd.getpwnam(run_as_user)
env = os.environ.copy()
env["HOME"] = pw_record.pw_dir
env["LOGNAME"] = run_as_user
env["USER"] = pw_record.pw_name

def preexec():
os.setgid(pw_record.pw_gid)
os.setuid(pw_record.pw_uid)

else:
env = None
preexec = None

full_output = ""
with subprocess.Popen(
with subprocess.Popen( # pylint: disable=subprocess-popen-preexec-fn
cmd,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True,
env=env,
preexec_fn=preexec,
) as proc:
while proc.poll() is None:
err = read_stream(proc.stderr)
Expand Down Expand Up @@ -203,9 +224,9 @@ def chdir(self, directory):
# directory = self.getcwd() + "/" + directory
directory = self.path(directory)
if not self.exists(directory):
raise ValueError("Directory does not exist")
raise ValueError(f"Directory '{directory}' does not exist")
if not self.isdir(directory):
raise ValueError("Given location is not a directory")
raise ValueError(f"The given location '{directory}' is not a directory")
os.chdir(directory)

def pushd(self, directory):
Expand Down

0 comments on commit 8503f01

Please sign in to comment.