From e59fe433c7e013d76a26c9e268a4d3d69c2afb43 Mon Sep 17 00:00:00 2001
From: xuezhixin <xuezhixin@uniontech.com>
Date: Fri, 10 Nov 2023 14:02:37 +0800
Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0subprocess=E9=80=9A=E8=BF=87?=
 =?UTF-8?q?=E5=8A=9F=E8=83=BD=E5=B9=B6=E8=AE=B0=E5=BD=95=E6=97=A5=E5=BF=97?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

---
 sysmig_agent/share.py | 47 +++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 47 insertions(+)

diff --git a/sysmig_agent/share.py b/sysmig_agent/share.py
index 57bef1e..9e7bd35 100644
--- a/sysmig_agent/share.py
+++ b/sysmig_agent/share.py
@@ -437,3 +437,50 @@ def get_new_osversion():
 
     else:
         sql_os_newversion('NULL')
+
+
+def run_subprocess(cmd="", print_cmd=True, print_output=True):
+    """Call the passed command and optionally log the called command (print_cmd=True) and its
+    output (print_output=True). Switching off printing the command can be useful in case it contains
+    a password in plain text.
+    """
+    cwdo = '/var/tmp/uos-migration/UOS_migration_log/mig_log.txt'
+    cwde = '/var/tmp/uos-migration/UOS_migration_log/mig_err.txt'
+    # fderr = open(cwde, 'a')
+    # from logging import *
+    # if print_cmd:
+    #     log.debug("Calling command '%s'" % cmd)
+
+    # Python 2.6 has a bug in shlex that interprets certain characters in a string as
+    # a NULL character. This is a workaround that encodes the string to avoid the issue.
+    if print_output:
+        fdout = open(cwdo, 'a')
+        fderr = open(cwde, 'a')
+    if sys.version_info[0] == 2 and sys.version_info[1] == 6:
+        cmd = cmd.encode("ascii")
+    # cmd = shlex.split(cmd, False)
+    process = subprocess.Popen(
+        cmd,
+        # stdout=subprocess.PIPE,
+        # stderr=subprocess.STDOUT,
+        stdout=fdout,
+        stderr=fderr,
+        bufsize=1,
+        shell=True
+    )
+    output = ""
+    try:
+        for line in iter(process.stdout.readline, b""):
+            output += line.decode()
+    except:
+        pass
+
+    #            loggerinst.info(line.decode().rstrip("\n"))
+
+    # Call communicate() to wait for the process to terminate so that we can get the return code by poll().
+    # It's just for py2.6, py2.7+/3 doesn't need this.
+    process.communicate()
+
+    return_code = process.poll()
+    return output, return_code
+
-- 
2.20.1

