Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions src/sonic-py-common/sonic_py_common/general.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import sys
import subprocess


def load_module_from_source(module_name, file_path):
Expand All @@ -23,3 +24,33 @@ def load_module_from_source(module_name, file_path):
sys.modules[module_name] = module

return module


def getstatusoutput_noshell(cmd):
Copy link
Copy Markdown
Collaborator

@qiluo-msft qiluo-msft Sep 14, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

getstatusoutput_noshell

Please add unit tests to cover new functions. #Closed

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure, working on UT

"""
This function implements getstatusoutput API from subprocess module
but using shell=False to prevent shell injection.
"""
p = subprocess.run(cmd, capture_output=True, universal_newlines=True)
status, output = p.returncode, p.stdout
if output[-1:] == '\n':
output = output[:-1]
return (status, output)


def getstatusoutput_noshell_pipe(cmd1, cmd2):
"""
This function implements getstatusoutput API from subprocess module
but using shell=False to prevent shell injection. Input command includes
pipe command.
"""
status = 0
with subprocess.Popen(cmd1, universal_newlines=True, stdout=subprocess.PIPE) as p1:
with subprocess.Popen(cmd2, universal_newlines=True, stdin=p1.stdout, stdout=subprocess.PIPE) as p2:
output = p2.communicate()[0]
p1.wait()
if p1.returncode != 0 and p2.returncode != 0:
Copy link
Copy Markdown
Collaborator

@qiluo-msft qiluo-msft Sep 15, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

and

and -> or #Closed

status = 1
Copy link
Copy Markdown
Collaborator

@qiluo-msft qiluo-msft Sep 14, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

status = 1

This is a general function, so hide information into status 0/1 is not recommended. Suggest return an array of status as the first element in the returned pair. #Closed

if output[-1:] == '\n':
output = output[:-1]
return (status, output)