[device/ragile] Mitigation for security vulnerability (#11744)

Signed-off-by: maipbui <maibui@microsoft.com>
#### Why I did it
The [xml.etree.ElementTree](https://docs.python.org/3/library/xml.etree.elementtree.html#module-xml.etree.ElementTree) module is not secure against maliciously constructed data.
`os` - not secure against maliciously constructed input and dangerous if used to evaluate dynamic content
`subprocess.getstatusoutput` is dangerous because include shell=True in the implementation
#### How I did it
Remove xml. Use [lxml](https://pypi.org/project/lxml/) XML parsers package that prevent potentially malicious operation.
Replace `os` by `subprocess`
Use command as an array instead of string
Use `getstatusoutput_noshell` in `sonic_py_common` lib
This commit is contained in:
Mai Bui 2022-11-29 11:54:37 -05:00 committed by GitHub
parent 32eca3ff75
commit 95bb7f3b78
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
21 changed files with 234 additions and 234 deletions

View File

@ -5,11 +5,10 @@
# * PSU # * PSU
# #
import os import os
import xml.etree.ElementTree as ET
import glob import glob
from fru import * from fru import *
from fantlv import * from fantlv import *
from lxml import etree as ET
MAILBOX_DIR = "/sys/bus/i2c/devices/" MAILBOX_DIR = "/sys/bus/i2c/devices/"

View File

@ -6,8 +6,8 @@
* PSU * PSU
""" """
import os import os
import xml.etree.ElementTree as ET
import glob import glob
from lxml import etree as ET
MAILBOX_DIR = "/sys/bus/i2c/devices/" MAILBOX_DIR = "/sys/bus/i2c/devices/"
PORTS_DIR = "/sys/class/net/" PORTS_DIR = "/sys/class/net/"

View File

@ -5,8 +5,8 @@
# * PSU # * PSU
# #
import os import os
import xml.etree.ElementTree as ET
import glob import glob
from lxml import etree as ET
MAILBOX_DIR = "/sys/bus/i2c/devices/" MAILBOX_DIR = "/sys/bus/i2c/devices/"
PORTS_DIR = "/sys/class/net/" PORTS_DIR = "/sys/class/net/"

View File

@ -11,6 +11,7 @@
import os.path import os.path
import sys import sys
import ast
sys.path.append('/usr/share/sonic/platform/plugins') sys.path.append('/usr/share/sonic/platform/plugins')
import pddfparse import pddfparse
import json import json
@ -170,7 +171,7 @@ class FanUtil(FanBase):
print("Setting fan speed is not allowed !") print("Setting fan speed is not allowed !")
return False return False
else: else:
duty_cycle_to_pwm = eval(plugin_data['FAN']['duty_cycle_to_pwm']) duty_cycle_to_pwm = ast.literal_eval(plugin_data['FAN']['duty_cycle_to_pwm'])
pwm = duty_cycle_to_pwm(val) pwm = duty_cycle_to_pwm(val)
print("New Speed: %d%% - PWM value to be set is %d\n" % (val, pwm)) print("New Speed: %d%% - PWM value to be set is %d\n" % (val, pwm))

View File

@ -5,9 +5,9 @@
# * PSU # * PSU
# #
import os import os
import xml.etree.ElementTree as ET
import glob import glob
from eepromutil.fru import * from eepromutil.fru import *
from lxml import etree as ET
MAILBOX_DIR = "/sys/bus/i2c/devices/" MAILBOX_DIR = "/sys/bus/i2c/devices/"
CONFIG_NAME = "dev.xml" CONFIG_NAME = "dev.xml"

View File

@ -7,7 +7,6 @@ from subprocess import Popen, PIPE
from re import findall from re import findall
from os.path import exists from os.path import exists
INNODISK = "iSmart -d {}"
NOT_AVAILABLE = "N/A" NOT_AVAILABLE = "N/A"
class SsdUtil(SsdBase): class SsdUtil(SsdBase):
@ -30,7 +29,8 @@ class SsdUtil(SsdBase):
self.temperature = NOT_AVAILABLE self.temperature = NOT_AVAILABLE
self.health = NOT_AVAILABLE self.health = NOT_AVAILABLE
self.ssd_info = self._execute_shell(INNODISK.format(diskdev)) INNODISK = ["iSmart", "-d", diskdev]
self.ssd_info = self._execute_shell(INNODISK)
self.model = self._parse_re(r'Model Name:\s*(.+?)\n', self.ssd_info) self.model = self._parse_re(r'Model Name:\s*(.+?)\n', self.ssd_info)
self.serial = self._parse_re(r'Serial Number:\s*(.+?)\n', self.ssd_info) self.serial = self._parse_re(r'Serial Number:\s*(.+?)\n', self.ssd_info)
@ -39,7 +39,7 @@ class SsdUtil(SsdBase):
self.health = self._parse_re(r'Health:\s*(.+?)', self.ssd_info) self.health = self._parse_re(r'Health:\s*(.+?)', self.ssd_info)
def _execute_shell(self, cmd): def _execute_shell(self, cmd):
process = Popen(cmd.split(), universal_newlines=True, stdout=PIPE) process = Popen(cmd, universal_newlines=True, stdout=PIPE)
output, _ = process.communicate() output, _ = process.communicate()
return output return output

View File

@ -4,8 +4,10 @@
import click import click
import os import os
import time import time
from ragileconfig import GLOBALCONFIG, GLOBALINITPARAM, GLOBALINITCOMMAND, MAC_LED_RESET, STARTMODULE, i2ccheck_params import subprocess
from ragileutil import rgpciwr, os_system, rgi2cset, io_wr from ragileconfig import GLOBALCONFIG, GLOBALINITPARAM, MAC_LED_RESET, STARTMODULE, i2ccheck_params
from ragileutil import rgpciwr, rgi2cset, io_wr
from sonic_py_common.general import getstatusoutput_noshell, getstatusoutput_noshell_pipe
CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help']) CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])
@ -24,7 +26,7 @@ class AliasedGroup(click.Group):
def log_os_system(cmd): def log_os_system(cmd):
u'''execute shell command''' u'''execute shell command'''
status, output = os_system(cmd) status, output = getstatusoutput_noshell(cmd)
if status: if status:
print(output) print(output)
return status, output return status, output
@ -44,7 +46,7 @@ def write_sysfs_value(reg_name, value):
def check_driver(): def check_driver():
u'''whether there is driver start with rg''' u'''whether there is driver start with rg'''
status, output = log_os_system("lsmod | grep rg | wc -l") status, output = getstatusoutput_noshell_pipe(["lsmod"], ["grep", "rg"], ["wc", "-l"])
#System execution error #System execution error
if status: if status:
return False return False
@ -68,61 +70,61 @@ def get_pid(name):
return ret return ret
def start_avs_ctrl(): def start_avs_ctrl():
cmd = "nohup avscontrol.py start >/dev/null 2>&1 &" cmd = ["avscontrol.py", "start"]
rets = get_pid("avscontrol.py") rets = get_pid("avscontrol.py")
if len(rets) == 0: if len(rets) == 0:
os.system(cmd) subprocess.Popen(cmd)
def start_fan_ctrl(): def start_fan_ctrl():
if STARTMODULE['fancontrol'] == 1: if STARTMODULE['fancontrol'] == 1:
cmd = "nohup fancontrol.py start >/dev/null 2>&1 &" cmd = ["fancontrol.py", "start"]
rets = get_pid("fancontrol.py") rets = get_pid("fancontrol.py")
if len(rets) == 0: if len(rets) == 0:
os.system(cmd) subprocess.Popen(cmd)
def starthal_fanctrl(): def starthal_fanctrl():
if STARTMODULE.get('hal_fanctrl',0) == 1: if STARTMODULE.get('hal_fanctrl',0) == 1:
cmd = "nohup hal_fanctrl.py start >/dev/null 2>&1 &" cmd = ["hal_fanctrl.py", "start"]
rets = get_pid("hal_fanctrl.py") rets = get_pid("hal_fanctrl.py")
if len(rets) == 0: if len(rets) == 0:
os.system(cmd) subprocess.Popen(cmd)
def starthal_ledctrl(): def starthal_ledctrl():
if STARTMODULE.get('hal_ledctrl',0) == 1: if STARTMODULE.get('hal_ledctrl',0) == 1:
cmd = "nohup hal_ledctrl.py start >/dev/null 2>&1 &" cmd = ["hal_ledctrl.py", "start"]
rets = get_pid("hal_ledctrl.py") rets = get_pid("hal_ledctrl.py")
if len(rets) == 0: if len(rets) == 0:
os.system(cmd) subprocess.Popen(cmd)
def start_dev_monitor(): def start_dev_monitor():
if STARTMODULE.get('dev_monitor',0) == 1: if STARTMODULE.get('dev_monitor',0) == 1:
cmd = "nohup dev_monitor.py start >/dev/null 2>&1 &" cmd = ["dev_monitor.py", "start"]
rets = get_pid("dev_monitor.py") rets = get_pid("dev_monitor.py")
if len(rets) == 0: if len(rets) == 0:
os.system(cmd) subprocess.Popen(cmd)
def start_slot_monitor(): def start_slot_monitor():
if STARTMODULE.get('slot_monitor',0) == 1: if STARTMODULE.get('slot_monitor',0) == 1:
cmd = "nohup slot_monitor.py start >/dev/null 2>&1 &" cmd = ["slot_monitor.py", "start"]
rets = get_pid("slot_monitor.py") rets = get_pid("slot_monitor.py")
if len(rets) == 0: if len(rets) == 0:
os.system(cmd) subprocess.Popen(cmd)
def stop_fan_ctrl(): def stop_fan_ctrl():
u'''disable fan timer service''' u'''disable fan timer service'''
if STARTMODULE['fancontrol'] == 1: if STARTMODULE['fancontrol'] == 1:
rets = get_pid("fancontrol.py") # rets = get_pid("fancontrol.py") #
for ret in rets: for ret in rets:
cmd = "kill "+ ret cmd = ["kill", ret]
os.system(cmd) subprocess.call(cmd)
return True return True
def stophal_ledctrl(): def stophal_ledctrl():
if STARTMODULE.get('hal_ledctrl',0) == 1: if STARTMODULE.get('hal_ledctrl',0) == 1:
rets = get_pid("hal_ledctrl.py") rets = get_pid("hal_ledctrl.py")
for ret in rets: for ret in rets:
cmd = "kill "+ ret cmd = ["kill", ret]
os.system(cmd) subprocess.call(cmd)
return True return True
@ -131,8 +133,8 @@ def stop_dev_monitor():
if STARTMODULE.get('dev_monitor',0) == 1: if STARTMODULE.get('dev_monitor',0) == 1:
rets = get_pid("dev_monitor.py") # rets = get_pid("dev_monitor.py") #
for ret in rets: for ret in rets:
cmd = "kill "+ ret cmd = ["kill", ret]
os.system(cmd) subprocess.call(cmd)
return True return True
def stop_slot_monitor(): def stop_slot_monitor():
@ -140,31 +142,31 @@ def stop_slot_monitor():
if STARTMODULE.get('slot_monitor',0) == 1: if STARTMODULE.get('slot_monitor',0) == 1:
rets = get_pid("slot_monitor.py") # rets = get_pid("slot_monitor.py") #
for ret in rets: for ret in rets:
cmd = "kill "+ ret cmd = ["kill", ret]
os.system(cmd) subprocess.call(cmd)
return True return True
def rm_dev(bus, loc): def rm_dev(bus, loc):
cmd = "echo 0x%02x > /sys/bus/i2c/devices/i2c-%d/delete_device" % (loc, bus)
devpath = "/sys/bus/i2c/devices/%d-%04x"%(bus, loc) devpath = "/sys/bus/i2c/devices/%d-%04x"%(bus, loc)
if os.path.exists(devpath): if os.path.exists(devpath):
log_os_system(cmd) with open("/sys/bus/i2c/devices/i2c-%d/delete_device" % bus, 'w') as f:
f.write('0x%02x\n' % loc)
def add_dev(name, bus, loc): def add_dev(name, bus, loc):
if name == "lm75": if name == "lm75":
time.sleep(0.1) time.sleep(0.1)
pdevpath = "/sys/bus/i2c/devices/i2c-%d/" % (bus) pdevpath = "/sys/bus/i2c/devices/i2c-%d/" % (bus)
for i in range(1, 100):#wait for mother-bus generationmaximum wait time is 10s for i in range(1, 100):#wait for mother-bus generationmaximum wait time is 10s
if os.path.exists(pdevpath) == True: if os.path.exists(pdevpath) is True:
break break
time.sleep(0.1) time.sleep(0.1)
if i % 10 == 0: if i % 10 == 0:
click.echo("%%DEVICE_I2C-INIT: %s not found, wait 0.1 second ! i %d " % (pdevpath,i)) click.echo("%%DEVICE_I2C-INIT: %s not found, wait 0.1 second ! i %d " % (pdevpath,i))
cmd = "echo %s 0x%02x > /sys/bus/i2c/devices/i2c-%d/new_device" % (name, loc, bus)
devpath = "/sys/bus/i2c/devices/%d-%04x"%(bus, loc) devpath = "/sys/bus/i2c/devices/%d-%04x"%(bus, loc)
if os.path.exists(devpath) == False: if os.path.exists(devpath) is False:
os.system(cmd) with open("/sys/bus/i2c/devices/i2c-%d/new_device" % bus, 'w') as f:
f.write('%s 0x%02x\n' % (name, loc))
def removedevs(): def removedevs():
devs = GLOBALCONFIG["DEVS"] devs = GLOBALCONFIG["DEVS"]
@ -177,8 +179,7 @@ def adddevs():
add_dev(devs[dev]["name"], devs[dev]["bus"] , devs[dev]["loc"]) add_dev(devs[dev]["name"], devs[dev]["bus"] , devs[dev]["loc"])
def checksignaldriver(name): def checksignaldriver(name):
modisexistcmd = "lsmod | grep %s | wc -l" % name status, output = getstatusoutput_noshell_pipe(["lsmod"], ["grep", name], ["wc", "-l"])
status, output = log_os_system(modisexistcmd)
#System execution error #System execution error
if status: if status:
return False return False
@ -188,17 +189,17 @@ def checksignaldriver(name):
return False return False
def adddriver(name, delay): def adddriver(name, delay):
cmd = "modprobe %s" % name cmd = ["modprobe", name]
if delay != 0: if delay != 0:
time.sleep(delay) time.sleep(delay)
if checksignaldriver(name) != True: if not checksignaldriver(name):
log_os_system(cmd) getstatusoutput_noshell(cmd)
def removedriver(name, delay): def removedriver(name, delay):
realname = name.lstrip().split(" ")[0]; realname = name.lstrip().split(" ")[0];
cmd = "rmmod -f %s" % realname cmd = ["rmmod", "-f", realname]
if checksignaldriver(realname): if checksignaldriver(realname):
log_os_system(cmd) getstatusoutput_noshell(cmd)
def removedrivers(): def removedrivers():
u'''remove all drivers''' u'''remove all drivers'''

View File

@ -5,6 +5,7 @@ import os
import time import time
import traceback import traceback
import glob import glob
import subprocess
from rgutil.logutil import Logger from rgutil.logutil import Logger
from ragileutil import wait_docker from ragileutil import wait_docker
@ -196,7 +197,7 @@ class FanControl(object):
loc = item_slot.get("loc") loc = item_slot.get("loc")
offset = item_slot.get("offset") offset = item_slot.get("offset")
ind, val = rgi2cget(bus, loc, offset) ind, val = rgi2cget(bus, loc, offset)
if ind == True: if ind is True:
retval = val retval = val
else: else:
totalerr -= 1 totalerr -= 1
@ -259,7 +260,7 @@ class FanControl(object):
loc = item_psu.get("loc") loc = item_psu.get("loc")
offset = item_psu.get("offset") offset = item_psu.get("offset")
ind, val = rgi2cget(bus, loc, offset) ind, val = rgi2cget(bus, loc, offset)
if ind == True: if ind is True:
retval = val retval = val
else: else:
totalerr -= 1 totalerr -= 1
@ -321,7 +322,7 @@ class FanControl(object):
presentaddr = presentstatus.get("offset") presentaddr = presentstatus.get("offset")
presentbit = presentstatus.get("bit") presentbit = presentstatus.get("bit")
ind, val = rgi2cget(presentbus, presentloc, presentaddr) ind, val = rgi2cget(presentbus, presentloc, presentaddr)
if ind == True: if ind is True:
val_t = (int(val, 16) & (1 << presentbit)) >> presentbit val_t = (int(val, 16) & (1 << presentbit)) >> presentbit
logger.debug( logger.debug(
DEBUG_COMMON, DEBUG_COMMON,
@ -343,7 +344,7 @@ class FanControl(object):
statusaddr = motor.get("offset", None) statusaddr = motor.get("offset", None)
statusbit = motor.get("bit", None) statusbit = motor.get("bit", None)
ind, val = rgi2cget(statusbus, statusloc, statusaddr) ind, val = rgi2cget(statusbus, statusloc, statusaddr)
if ind == True: if ind is True:
val_t = (int(val, 16) & (1 << statusbit)) >> statusbit val_t = (int(val, 16) & (1 << statusbit)) >> statusbit
logger.debug( logger.debug(
DEBUG_COMMON, DEBUG_COMMON,
@ -446,7 +447,7 @@ class FanControl(object):
try: try:
cur_fan_status = [] cur_fan_status = []
ret = self.checkfan(cur_fan_status) ret = self.checkfan(cur_fan_status)
if ret == True: if ret is True:
self.set_fan_attr(cur_fan_status) self.set_fan_attr(cur_fan_status)
self.fan_present_num(cur_fan_status) self.fan_present_num(cur_fan_status)
logger.debug(DEBUG_COMMON, "%%policy:get_fan_status success") logger.debug(DEBUG_COMMON, "%%policy:get_fan_status success")
@ -469,7 +470,7 @@ class FanControl(object):
try: try:
curPsuStatus = [] curPsuStatus = []
ret = self.checkpsu(curPsuStatus) ret = self.checkpsu(curPsuStatus)
if ret == True: if ret is True:
self.normal_psu_num(curPsuStatus) self.normal_psu_num(curPsuStatus)
logger.debug(DEBUG_COMMON, "%%policy:get_psu_status success") logger.debug(DEBUG_COMMON, "%%policy:get_psu_status success")
return 0 return 0
@ -499,7 +500,7 @@ class FanControl(object):
try: try:
monitortemp = [] monitortemp = []
ret = self.gettemp(monitortemp) ret = self.gettemp(monitortemp)
if ret == True: if ret is True:
self.get_monitor_temp(monitortemp) self.get_monitor_temp(monitortemp)
logger.debug(DEBUG_COMMON, "%%policy:get_temp_status success") logger.debug(DEBUG_COMMON, "%%policy:get_temp_status success")
return 0 return 0
@ -511,9 +512,9 @@ class FanControl(object):
def get_mac_status_bcmcmd(self): def get_mac_status_bcmcmd(self):
try: try:
if wait_docker(timeout=0) == True: if wait_docker(timeout=0) is True:
sta, ret = get_mac_temp() sta, ret = get_mac_temp()
if sta == True: if sta is True:
self._mac_aver = float(ret.get("average", self._mac_aver)) self._mac_aver = float(ret.get("average", self._mac_aver))
self._mac_max = float(ret.get("maximum", self._mac_max)) self._mac_max = float(ret.get("maximum", self._mac_max))
logger.debug( logger.debug(
@ -532,7 +533,7 @@ class FanControl(object):
def get_mac_status_sysfs(self, conf): def get_mac_status_sysfs(self, conf):
try: try:
sta, ret = get_mac_temp_sysfs(conf) sta, ret = get_mac_temp_sysfs(conf)
if sta == True: if sta is True:
self._mac_aver = float(ret) / 1000 self._mac_aver = float(ret) / 1000
self._mac_max = float(ret) / 1000 self._mac_max = float(ret) / 1000
logger.debug( logger.debug(
@ -578,7 +579,7 @@ class FanControl(object):
try: try:
curSlotStatus = [] curSlotStatus = []
ret = self.checkslot(curSlotStatus) ret = self.checkslot(curSlotStatus)
if ret == True: if ret is True:
self.set_slot_attr(curSlotStatus) self.set_slot_attr(curSlotStatus)
logger.debug(DEBUG_COMMON, "%%policy:get_slot_status success") logger.debug(DEBUG_COMMON, "%%policy:get_slot_status success")
except AttributeError as e: except AttributeError as e:
@ -631,8 +632,8 @@ class FanControl(object):
self.check_crit() self.check_crit()
if ( if (
self.critnum == 0 self.critnum == 0
and self.check_warn() == False and self.check_warn() is False
and self.detect_fan_status() == True and self.detect_fan_status() is True
): ):
self.fanctrol() self.fanctrol()
self.check_dev_err() self.check_dev_err()
@ -768,13 +769,13 @@ class FanControl(object):
fanstatus = self.check_fan_status() fanstatus = self.check_fan_status()
psustatus = self.check_psu_status() psustatus = self.check_psu_status()
if ( if (
self.check_temp_crit() == True self.check_temp_crit() is True
or fanstatus == "red" or fanstatus == "red"
or psustatus == "red" or psustatus == "red"
): ):
status = "red" status = "red"
elif ( elif (
self.check_temp_warn() == True self.check_temp_warn() is True
or fanstatus == "yellow" or fanstatus == "yellow"
or psustatus == "yellow" or psustatus == "yellow"
): ):
@ -864,7 +865,7 @@ class FanControl(object):
else: else:
mask = item.get("mask", 0xFF) mask = item.get("mask", 0xFF)
ind, val = rgi2cget(item["bus"], item["devno"], item["addr"]) ind, val = rgi2cget(item["bus"], item["devno"], item["addr"])
if ind == True: if ind is True:
setval = (int(val, 16) & ~mask) | item.get(color) setval = (int(val, 16) & ~mask) | item.get(color)
rgi2cset(item["bus"], item["devno"], item["addr"], setval) rgi2cset(item["bus"], item["devno"], item["addr"], setval)
else: else:
@ -884,12 +885,12 @@ class FanControl(object):
def check_warn(self): def check_warn(self):
try: try:
if self.check_temp_warn() == True: if self.check_temp_warn() is True:
logger.debug(DEBUG_FANCONTROL, "anti-shake start") logger.debug(DEBUG_FANCONTROL, "anti-shake start")
time.sleep(MONITOR_CONST.SHAKE_TIME) time.sleep(MONITOR_CONST.SHAKE_TIME)
logger.debug(DEBUG_FANCONTROL, "anti-shake end") logger.debug(DEBUG_FANCONTROL, "anti-shake end")
self.board_moni_msg() # re-read self.board_moni_msg() # re-read
if self.check_temp_warn() == True: if self.check_temp_warn() is True:
logger.warn("%%DEV_MONITOR-TEMP:The temperature of device is over warning value.") logger.warn("%%DEV_MONITOR-TEMP:The temperature of device is over warning value.")
self.set_fan_max_speed() # fan full speed self.set_fan_max_speed() # fan full speed
return True return True
@ -900,19 +901,19 @@ class FanControl(object):
def check_crit(self): def check_crit(self):
try: try:
if self.check_temp_crit() == True: if self.check_temp_crit() is True:
logger.debug(DEBUG_FANCONTROL, "anti-shake start") logger.debug(DEBUG_FANCONTROL, "anti-shake start")
time.sleep(MONITOR_CONST.SHAKE_TIME) time.sleep(MONITOR_CONST.SHAKE_TIME)
logger.debug(DEBUG_FANCONTROL, "anti-shake end") logger.debug(DEBUG_FANCONTROL, "anti-shake end")
self.board_moni_msg() # re-read self.board_moni_msg() # re-read
if self.check_temp_crit() == True: if self.check_temp_crit() is True:
logger.crit( logger.crit(
"%%DEV_MONITOR-TEMP:The temperature of device is over critical value.", "%%DEV_MONITOR-TEMP:The temperature of device is over critical value.",
) )
self.set_fan_max_speed() # fan full speed self.set_fan_max_speed() # fan full speed
self.critnum += 1 # anti-shake self.critnum += 1 # anti-shake
if self.critnum >= MONITOR_CONST.CRITICAL_NUM: if self.critnum >= MONITOR_CONST.CRITICAL_NUM:
os.system("reboot") subprocess.call(["reboot"])
logger.debug(DEBUG_FANCONTROL, "crit times:%d" % self.critnum) logger.debug(DEBUG_FANCONTROL, "crit times:%d" % self.critnum)
else: else:
self.critnum = 0 self.critnum = 0
@ -929,7 +930,7 @@ def callback():
def do_fan_ctrl(fanctrl): def do_fan_ctrl(fanctrl):
ret = fanctrl.board_moni_msg() ret = fanctrl.board_moni_msg()
if ret == True: if ret is True:
logger.debug(DEBUG_FANCONTROL, "%%policy:start_fan_ctrl") logger.debug(DEBUG_FANCONTROL, "%%policy:start_fan_ctrl")
fanctrl.start_fan_ctrl() fanctrl.start_fan_ctrl()
else: else:

View File

@ -9,11 +9,6 @@
# Copyright: (c) rd 2018 # Copyright: (c) rd 2018
# ------------------------------------------------------------------------- # -------------------------------------------------------------------------
import sys import sys
if sys.version_info >= (3, 0):
import subprocess as commands
else:
import commands
import os import os
import re import re
import syslog import syslog
@ -49,6 +44,7 @@ from ragileconfig import (
try: try:
from eepromutil.fru import ipmifru from eepromutil.fru import ipmifru
from sonic_py_common.general import getstatusoutput_noshell, getstatusoutput_noshell_pipe
except Exception or SystemExit: except Exception or SystemExit:
pass pass
@ -344,21 +340,21 @@ class SETMACException(Exception):
def checkinput(b): def checkinput(b):
if b.isdigit() == False: if b.isdigit() is False:
raise Exception("Ivalid Number") raise Exception("Ivalid Number")
if int(b) > 0xFF or int(b) < 0: if int(b) > 0xFF or int(b) < 0:
raise Exception("Out of area") raise Exception("Out of area")
def checkinputproduct(b): def checkinputproduct(b):
if b.isalnum() == False: if b.isalnum() is False:
raise Exception("Invalid string") raise Exception("Invalid string")
def getInputSetmac(val): def getInputSetmac(val):
bia = val.boardInfoArea bia = val.boardInfoArea
pia = val.productInfoArea pia = val.productInfoArea
if bia != None: if bia is not None:
a = raw_input("[Board Card]Product Serial Number:") a = raw_input("[Board Card]Product Serial Number:")
if len(a) != 13: if len(a) != 13:
raise Exception("Invalid Serial Number length") raise Exception("Invalid Serial Number length")
@ -368,7 +364,7 @@ def getInputSetmac(val):
checkinput(b) checkinput(b)
b = "%0x" % int(b) b = "%0x" % int(b)
bia.boardextra1 = b.upper() bia.boardextra1 = b.upper()
if pia != None: if pia is not None:
a = raw_input("[Product Area]Product Serial Number:") a = raw_input("[Product Area]Product Serial Number:")
if len(a) != 13: if len(a) != 13:
raise Exception("Invalid Serial Number") raise Exception("Invalid Serial Number")
@ -633,7 +629,7 @@ class AVSUTIL:
macavs = 0 macavs = 0
name = MAC_DEFAULT_PARAM["sdkreg"] name = MAC_DEFAULT_PARAM["sdkreg"]
ret, status = getSdkReg(name) ret, status = getSdkReg(name)
if ret == False: if ret is False:
return False return False
status = strtoint(status) status = strtoint(status)
# shift operation # shift operation
@ -711,8 +707,8 @@ class BMC:
def getSdkReg(reg): def getSdkReg(reg):
try: try:
cmd = "bcmcmd -t 1 'getr %s ' < /dev/null" % reg cmd = ["bcmcmd", "-t", "1", 'getr '+str(reg)]
ret, result = os_system(cmd) ret, result = getstatusoutput_noshell(cmd)
result_t = result.strip().replace("\r", "").replace("\n", "") result_t = result.strip().replace("\r", "").replace("\n", "")
if ret != 0 or "Error:" in result_t: if ret != 0 or "Error:" in result_t:
return False, result return False, result
@ -807,8 +803,8 @@ def get_mac_temp():
result = {} result = {}
# wait_docker() # wait_docker()
# exec twice, get the second result # exec twice, get the second result
os_system('bcmcmd -t 1 "show temp" < /dev/null') getstatusoutput_noshell(["bcmcmd", "-t", "1", "show temp"])
ret, log = os_system('bcmcmd -t 1 "show temp" < /dev/null') ret, log = getstatusoutput_noshell(["bcmcmd", "-t", "1", "show temp"])
if ret: if ret:
return False, result return False, result
else: else:
@ -875,21 +871,21 @@ def restartDockerService(force=False):
"teamd", "teamd",
"pmon", "pmon",
] ]
ret, status = os_system("docker ps") ret, status = getstatusoutput_noshell(["docker", "ps"])
if ret == 0: if ret == 0:
for tmpname in container_name: for tmpname in container_name:
if tmpname not in status: if tmpname not in status:
if force == True: if force == True:
os_system("docker restart %s" % tmpname) getstatusoutput_noshell(["docker", "restart", tmpname])
else: else:
os_system("systemctl restart %s" % tmpname) getstatusoutput_noshell(["systemctl", "restart", tmpname])
def wait_dhcp(timeout): def wait_dhcp(timeout):
time_cnt = 0 time_cnt = 0
while True: while True:
try: try:
ret, status = os_system("systemctl status dhcp_relay.service") ret, status = getstatusoutput_noshell(["systemctl", "status", "dhcp_relay.service"])
if (ret == 0 and "running" in status) or "SUCCESS" in status: if (ret == 0 and "running" in status) or "SUCCESS" in status:
break break
else: else:
@ -1028,10 +1024,12 @@ def isValidMac(mac):
def util_setmac(eth, mac): def util_setmac(eth, mac):
rulefile = "/etc/udev/rules.d/70-persistent-net.rules" rulefile = "/etc/udev/rules.d/70-persistent-net.rules"
if isValidMac(mac) == False: if isValidMac(mac) is False:
return False, "MAC invaild" return False, "MAC invaild"
cmd = "ethtool -e %s | grep 0x0010 | awk '{print \"0x\"$13$12$15$14}'" % eth cmd1 = ["ethtool", "-e", eth]
ret, log = os_system(cmd) cmd2 = ["grep", "0x0010"]
cmd3 = ["awk", '{print \"0x\"$13$12$15$14}']
ret, log = getstatusoutput_noshell_pipe(cmd1, cmd2, cmd3)
log_debug(log) log_debug(log)
magic = "" magic = ""
if ret == 0 and len(log): if ret == 0 and len(log):
@ -1039,22 +1037,22 @@ def util_setmac(eth, mac):
macs = mac.upper().split(":") macs = mac.upper().split(":")
# chage ETH0 to value after setmac # chage ETH0 to value after setmac
ifconfigcmd = "ifconfig eth0 hw ether %s" % mac ifconfigcmd = ["ifconfig", "eth0", "hw", "ether", mac]
log_debug(ifconfigcmd) log_debug(ifconfigcmd)
ret, status = os_system(ifconfigcmd) ret, status = getstatusoutput_noshell(ifconfigcmd)
if ret: if ret:
raise SETMACException("software set Internet card MAC error") raise SETMACException("software set Internet card MAC error")
index = 0 index = 0
for item in macs: for item in macs:
cmd = "ethtool -E %s magic %s offset %d value 0x%s" % (eth, magic, index, item) cmd = ["ethtool", "-E", eth, "magic", magic, "offset", str(offset), "value", "0x"+str(item)]
log_debug(cmd) log_debug(cmd)
index += 1 index += 1
ret, log = os_system(cmd) ret, log = getstatusoutput_noshell(cmd)
if ret != 0: if ret != 0:
raise SETMACException("set hardware Internet card MAC error") raise SETMACException("set hardware Internet card MAC error")
# get value after setting # get value after setting
cmd_t = "ethtool -e eth0 offset 0 length 6" cmd_t = ["ethtool", "-e", "eth0", "offset", "0", "length", "6"]
ret, log = os_system(cmd_t) ret, log = getstatusoutput_noshell(cmd_t)
m = re.split(":", log)[-1].strip().upper() m = re.split(":", log)[-1].strip().upper()
mac_result = m.upper().split(" ") mac_result = m.upper().split(" ")
@ -1143,7 +1141,7 @@ def changeTypeValue(_value, type1, tips, example):
release_mac += name[i * 2 : i * 2 + 2] release_mac += name[i * 2 : i * 2 + 2]
else: else:
release_mac += ":" + name[i * 2 : i * 2 + 2] release_mac += ":" + name[i * 2 : i * 2 + 2]
if isValidMac(release_mac) == True: if isValidMac(release_mac) is True:
_value[type1] = release_mac _value[type1] = release_mac
else: else:
raise SETMACException("MAC address invaild, check please") raise SETMACException("MAC address invaild, check please")
@ -1158,7 +1156,7 @@ def changeTypeValue(_value, type1, tips, example):
else: else:
raise SETMACException("Version is not number, check please") raise SETMACException("Version is not number, check please")
elif type1 == TLV_CODE_SERIAL_NUMBER: elif type1 == TLV_CODE_SERIAL_NUMBER:
if name.isalnum() == False: if name.isalnum() is False:
raise SETMACException("Serial Number invaild string, check please") raise SETMACException("Serial Number invaild string, check please")
elif len(name) != 13: elif len(name) != 13:
raise SETMACException("Serial Number length incorrect, check please") raise SETMACException("Serial Number length incorrect, check please")
@ -1185,11 +1183,11 @@ def generate_ext(cardid):
def rgi2cget(bus, devno, address): def rgi2cget(bus, devno, address):
command_line = "i2cget -f -y %d 0x%02x 0x%02x " % (bus, devno, address) command_line = ["i2cget", "-f", "-y", str(bus), "0x%02x"%devno, "0x%02x"%address]
retrytime = 6 retrytime = 6
ret_t = "" ret_t = ""
for i in range(retrytime): for i in range(retrytime):
ret, ret_t = os_system(command_line) ret, ret_t = getstatusoutput_noshell(command_line)
if ret == 0: if ret == 0:
return True, ret_t return True, ret_t
time.sleep(0.1) time.sleep(0.1)
@ -1197,11 +1195,11 @@ def rgi2cget(bus, devno, address):
def rgi2cset(bus, devno, address, byte): def rgi2cset(bus, devno, address, byte):
command_line = "i2cset -f -y %d 0x%02x 0x%02x 0x%02x" % (bus, devno, address, byte) command_line = ["i2cset", "-f", "-y", str(bus), "0x%02x"%devno, "0x%02x"%address, "0x%02x"%byte]
retrytime = 6 retrytime = 6
ret_t = "" ret_t = ""
for i in range(retrytime): for i in range(retrytime):
ret, ret_t = os_system(command_line) ret, ret_t = getstatusoutput_noshell(command_line)
if ret == 0: if ret == 0:
return True, ret_t return True, ret_t
return False, ret_t return False, ret_t
@ -1252,30 +1250,30 @@ def rgpciwr(pcibus, slot, fn, bar, offset, data):
def rgsysset(location, value): def rgsysset(location, value):
command_line = "echo 0x%02x > %s" % (value, location)
retrytime = 6 retrytime = 6
ret_t = ""
for i in range(retrytime): for i in range(retrytime):
ret, ret_t = os_system(command_line) try:
if ret == 0: with open(location, 'w') as f:
return True, ret_t f.write('0x%02x\n' % value)
return False, ret_t except (IOError, FileNotFoundError) as e:
return False, str(e)
return True, ''
def rgi2cget_word(bus, devno, address): def rgi2cget_word(bus, devno, address):
command_line = "i2cget -f -y %d 0x%02x 0x%02x w" % (bus, devno, address) command_line = ["i2cget", "-f", "-y", str(bus), "0x%02x"%devno, "0x%02x"%address, 'w']
retrytime = 3 retrytime = 3
ret_t = "" ret_t = ""
for i in range(retrytime): for i in range(retrytime):
ret, ret_t = os_system(command_line) ret, ret_t = getstatusoutput_noshell(command_line)
if ret == 0: if ret == 0:
return True, ret_t return True, ret_t
return False, ret_t return False, ret_t
def rgi2cset_word(bus, devno, address, byte): def rgi2cset_word(bus, devno, address, byte):
command_line = "i2cset -f -y %d 0x%02x 0x%02x 0x%x w" % (bus, devno, address, byte) command_line = ["i2cset", "-f", "-y", str(bus), "0x%02x"%devno, "0x%02x"%address, "0x%02x"%byte, 'w']
os_system(command_line) getstatusoutput_noshell(command_line)
def fan_setmac(): def fan_setmac():
@ -1395,7 +1393,7 @@ def fac_fans_setmac_tlv(ret):
while True: while True:
print("Please input[%s]:" % "Serial Number") print("Please input[%s]:" % "Serial Number")
fan_sn = raw_input() fan_sn = raw_input()
if checkfansninput(fan_sn, fansntemp) == False: if checkfansninput(fan_sn, fansntemp) is False:
continue continue
fansntemp.append(fan_sn) fansntemp.append(fan_sn)
fan_sn = fan_sn + chr(0x00) fan_sn = fan_sn + chr(0x00)
@ -1404,7 +1402,7 @@ def fac_fans_setmac_tlv(ret):
while True: while True:
print("Please input[%s]:" % "hardware version") print("Please input[%s]:" % "hardware version")
hwinfo = raw_input() hwinfo = raw_input()
if checkfanhwinput(hwinfo) == False: if checkfanhwinput(hwinfo) is False:
continue continue
fan_hwinfo = hwinfo + chr(0x00) fan_hwinfo = hwinfo + chr(0x00)
fane2.typehwinfo = fan_hwinfo + chr(0x00) fane2.typehwinfo = fan_hwinfo + chr(0x00)
@ -1416,7 +1414,7 @@ def fac_fans_setmac_tlv(ret):
print("\n*******************************\n") print("\n*******************************\n")
util_show_fanse2(fans) util_show_fanse2(fans)
if getInputCheck("check input correctly or notYes/No):") == True: if getInputCheck("check input correctly or notYes/No):") is True:
for fan in fans: for fan in fans:
log_debug("ouput fan") log_debug("ouput fan")
fac_fan_setmac(fan) fac_fan_setmac(fan)
@ -1512,14 +1510,15 @@ def writeToEEprom(rst_arr):
elif dealtype == "io": elif dealtype == "io":
io_wr(E2_PROTECT["io_addr"], E2_PROTECT["close"]) io_wr(E2_PROTECT["io_addr"], E2_PROTECT["close"])
# deal last drivers # deal last drivers
os.system("rmmod at24 ") subprocess.call(["rmmod", "at24"])
os.system("modprobe at24 ") subprocess.call(["modprobe", "at24"])
os.system("rm -f /var/cache/sonic/decode-syseeprom/syseeprom_cache") subprocess.call(["rm", "-f", "/var/cache/sonic/decode-syseeprom/syseeprom_cache"])
def get_local_eth0_mac(): def get_local_eth0_mac():
cmd = "ifconfig eth0 |grep HWaddr" cmd1 = ["ifconfig", "eth0"]
print(os_system(cmd)) cmd2 = ["grep", "HWaddr"]
print(getstatusoutput_noshell_pipe(cmd1, cmd2))
def getonieversion(): def getonieversion():
@ -1581,13 +1580,13 @@ def fac_board_setmac():
) # add setmac time ) # add setmac time
rst, ret = generate_value(_value) rst, ret = generate_value(_value)
if ( if (
util_setmac("eth0", _value[TLV_CODE_MAC_BASE]) == True util_setmac("eth0", _value[TLV_CODE_MAC_BASE]) is True
): # set Internet cardIP ): # set Internet cardIP
writeToEEprom(rst) # write to e2 writeToEEprom(rst) # write to e2
# set BMC MAC # set BMC MAC
if "bmcsetmac" in FACTESTMODULE and FACTESTMODULE["bmcsetmac"] == 1: if "bmcsetmac" in FACTESTMODULE and FACTESTMODULE["bmcsetmac"] == 1:
bmcmac = createbmcMac(_value[TLV_CODE_MAC_BASE]) bmcmac = createbmcMac(_value[TLV_CODE_MAC_BASE])
if ipmi_set_mac(bmcmac) == True: if ipmi_set_mac(bmcmac) is True:
print("BMC MAC[%s]" % bmcmac) print("BMC MAC[%s]" % bmcmac)
else: else:
print("SET BMC MAC FAILED") print("SET BMC MAC FAILED")
@ -1605,12 +1604,12 @@ def fac_board_setmac():
def ipmi_set_mac(mac): def ipmi_set_mac(mac):
macs = mac.split(":") macs = mac.split(":")
cmdinit = "ipmitool raw 0x0c 0x01 0x01 0xc2 0x00" cmdinit = ["ipmitool", "raw", "0x0c", "0x01", "0x01", "0xc2", "0x00"]
cmdset = "ipmitool raw 0x0c 0x01 0x01 0x05" cmdset = ["ipmitool", "raw", "0x0c", "0x01", "0x01", "0x05"]
for ind in range(len(macs)): for ind in range(len(macs)):
cmdset += " 0x%02x" % int(macs[ind], 16) cmdset.append("0x%02x" % int(macs[ind], 16))
os_system(cmdinit) getstatusoutput_noshell(cmdinit)
ret, status = os_system(cmdset) ret, status = getstatusoutput_noshell(cmdset)
if ret: if ret:
RJPRINTERR("\n\n%s\n\n" % status) RJPRINTERR("\n\n%s\n\n" % status)
return False return False
@ -1637,8 +1636,8 @@ def bmc_setmac():
release_mac += name[i * 2 : i * 2 + 2] release_mac += name[i * 2 : i * 2 + 2]
else: else:
release_mac += ":" + name[i * 2 : i * 2 + 2] release_mac += ":" + name[i * 2 : i * 2 + 2]
if isValidMac(release_mac) == True: if isValidMac(release_mac) is True:
if ipmi_set_mac(release_mac) == True: if ipmi_set_mac(release_mac) is True:
return True return True
else: else:
RJPRINTERR("\nMAC address invaild, try again\n") RJPRINTERR("\nMAC address invaild, try again\n")
@ -1650,11 +1649,11 @@ def closeProtocol():
log_info("disable LLDP") log_info("disable LLDP")
sys.stdout.write(".") sys.stdout.write(".")
sys.stdout.flush() sys.stdout.flush()
os_system("systemctl stop lldp.service") getstatusoutput_noshell(["systemctl", "stop", "lldp.service"])
log_info("disable lldp service") log_info("disable lldp service")
sys.stdout.write(".") sys.stdout.write(".")
sys.stdout.flush() sys.stdout.flush()
os_system("systemctl stop bgp.service") getstatusoutput_noshell(["systemctl", "stop", "bgp.service"])
log_info("disable bgp service") log_info("disable bgp service")
sys.stdout.write(".") sys.stdout.write(".")
sys.stdout.flush() sys.stdout.flush()
@ -1678,8 +1677,8 @@ def checkSdkMem():
with open(file_name, "w") as f: with open(file_name, "w") as f:
f.write(file_data) f.write(file_data)
print("change SDK memory to 256, reboot required") print("change SDK memory to 256, reboot required")
os_system("sync") getstatusoutput_noshell(["sync"])
os_system("reboot") getstatusoutput_noshell(["reboot"])
########################################################################## ##########################################################################
@ -1868,26 +1867,21 @@ def getCardId():
return None return None
# ====================================
# execute shell command
# ====================================
def os_system(cmd):
status, output = commands.getstatusoutput(cmd)
return status, output
########################################### ###########################################
# get memory slot and number via DMI command # get memory slot and number via DMI command
########################################### ###########################################
def getsysmeminfo(): def getsysmeminfo():
ret, log = os_system("which dmidecode ") ret, log = getstatusoutput_noshell(["which", "dmidecode"])
if ret != 0 or len(log) <= 0: if ret != 0 or len(log) <= 0:
error = "cmd find dmidecode" error = "cmd find dmidecode"
return False, error return False, error
cmd = log + '|grep -P -A5 "Memory\s+Device"|grep Size|grep -v Range' cmd1 = [log]
cmd2 = ['grep', '-P', '-A5', "Memory\s+Device"]
cmd3 = ['grep', 'Size']
cmd4 = ['grep', '-v', 'Range']
# get total number first # get total number first
result = [] result = []
ret1, log1 = os_system(cmd) ret1, log1 = getstatusoutput_noshell_pipe(cmd1, cmd2, cmd3, cmd4)
if ret1 == 0 and len(log1): if ret1 == 0 and len(log1):
log1 = log1.lstrip() log1 = log1.lstrip()
arr = log1.split("\n") arr = log1.split("\n")
@ -1908,13 +1902,16 @@ def getsysmeminfo():
# return various arrays # return various arrays
########################################### ###########################################
def getsysmeminfo_detail(): def getsysmeminfo_detail():
ret, log = os_system("which dmidecode ") ret, log = getstatusoutput_noshell(["which", "dmidecode"])
if ret != 0 or len(log) <= 0: if ret != 0 or len(log) <= 0:
error = "cmd find dmidecode" error = "cmd find dmidecode"
return False, error return False, error
cmd = log + ' -t 17 | grep -A21 "Memory Device"' # 17 cmd1 = [log]
cmd2 = ['-t', '17']
cmd3 = ['grep', '-A21', "Memory Device"] # 17
cmd = ' '.join(cmd1) + ' '.join(cmd2) + ' '.join(cmd3)
# get total number # get total number
ret1, log1 = os_system(cmd) ret1, log1 = getstatusoutput_noshell_pipe(cmd1, cmd2, cmd3)
if ret1 != 0 or len(log1) <= 0: if ret1 != 0 or len(log1) <= 0:
return False, "command execution error[%s]" % cmd return False, "command execution error[%s]" % cmd
result_t = log1.split("--") result_t = log1.split("--")
@ -1935,13 +1932,13 @@ def getsysmeminfo_detail():
# get BIOS info via DMI command # get BIOS info via DMI command
########################################### ###########################################
def getDmiSysByType(type_t): def getDmiSysByType(type_t):
ret, log = os_system("which dmidecode ") ret, log = getstatusoutput_noshell(["which", "dmidecode"])
if ret != 0 or len(log) <= 0: if ret != 0 or len(log) <= 0:
error = "cmd find dmidecode" error = "cmd find dmidecode"
return False, error return False, error
cmd = log + " -t %s" % type_t cmd = [log] + ["-t", type_t]
# get total number # get total number
ret1, log1 = os_system(cmd) ret1, log1 = getstatusoutput_noshell(cmd)
if ret1 != 0 or len(log1) <= 0: if ret1 != 0 or len(log1) <= 0:
return False, "command execution error[%s]" % cmd return False, "command execution error[%s]" % cmd
its = log1.replace("\t", "").strip().split("\n") its = log1.replace("\t", "").strip().split("\n")
@ -2000,11 +1997,11 @@ def getUsbLocation():
# judge USB file # judge USB file
def getusbinfo(): def getusbinfo():
ret, path = getUsbLocation() ret, path = getUsbLocation()
if ret == False: if ret is False:
return False, "not usb exists" return False, "not usb exists"
str = os.path.join(path, "size") str = os.path.join(path, "size")
ret, value = getfilevalue(str) ret, value = getfilevalue(str)
if ret == True: if ret is True:
return ( return (
True, True,
{ {
@ -2017,9 +2014,10 @@ def getusbinfo():
def get_cpu_info(): def get_cpu_info():
cmd = "cat /proc/cpuinfo |grep processor -A18" # 17 cmd1 = ["cat", "/proc/cpuinfo"]
cmd2 = ["grep", "processor", "-A18"] # 17
ret, log1 = os_system(cmd) cmd = ' '.join(cmd1) + ' '.join(cmd2)
ret, log1 = getstatusoutput_noshell_pipe(cmd1, cmd2)
if ret != 0 or len(log1) <= 0: if ret != 0 or len(log1) <= 0:
return False, "command execution error[%s]" % cmd return False, "command execution error[%s]" % cmd
result_t = log1.split("--") result_t = log1.split("--")

View File

@ -37,14 +37,14 @@ class PcieUtil(PcieBase):
pciList = [] pciList = []
p1 = "^(\w+):(\w+)\.(\w)\s(.*)\s*\(*.*\)*" p1 = "^(\w+):(\w+)\.(\w)\s(.*)\s*\(*.*\)*"
p2 = "^.*:.*:.*:(\w+)\s*\(*.*\)*" p2 = "^.*:.*:.*:(\w+)\s*\(*.*\)*"
command1 = "sudo lspci" command1 = ["sudo", "lspci"]
command2 = "sudo lspci -n" command2 = ["sudo", "lspci", "-n"]
# run command 1 # run command 1
proc1 = subprocess.Popen(command1, shell=True, universal_newlines=True, stdout=subprocess.PIPE) proc1 = subprocess.Popen(command1, universal_newlines=True, stdout=subprocess.PIPE)
output1 = proc1.stdout.readlines() output1 = proc1.stdout.readlines()
proc1.communicate() proc1.communicate()
# run command 2 # run command 2
proc2 = subprocess.Popen(command2, shell=True, universal_newlines=True, stdout=subprocess.PIPE) proc2 = subprocess.Popen(command2, universal_newlines=True, stdout=subprocess.PIPE)
output2 = proc2.stdout.readlines() output2 = proc2.stdout.readlines()
proc2.communicate() proc2.communicate()

View File

@ -1,6 +1,6 @@
import os import os
import yaml import yaml
import subprocess
from sonic_py_common import device_info from sonic_py_common import device_info
@ -10,13 +10,13 @@ class Common:
PMON_PLATFORM_PATH = '/usr/share/sonic/platform/' PMON_PLATFORM_PATH = '/usr/share/sonic/platform/'
CONFIG_DIR = 'sonic_platform_config' CONFIG_DIR = 'sonic_platform_config'
HOST_CHK_CMD = "docker > /dev/null 2>&1" HOST_CHK_CMD = ["docker"]
def __init__(self): def __init__(self):
(self.platform, self.hwsku) = device_info.get_platform_and_hwsku() (self.platform, self.hwsku) = device_info.get_platform_and_hwsku()
def is_host(self): def is_host(self):
return os.system(self.HOST_CHK_CMD) == 0 return subprocess.call(self.HOST_CHK_CMD) == 0
def load_json_file(self, path): def load_json_file(self, path):
""" """

View File

@ -8,10 +8,10 @@
######################################################################## ########################################################################
try: try:
import subprocess
from sonic_platform_base.component_base import ComponentBase from sonic_platform_base.component_base import ComponentBase
from sonic_platform.regutil import Reg from sonic_platform.regutil import Reg
from sonic_platform.logger import logger from sonic_platform.logger import logger
from sonic_py_common.general import getstatusoutput_noshell
except ImportError as e: except ImportError as e:
raise ImportError(str(e) + "- required module not found") raise ImportError(str(e) + "- required module not found")
@ -70,12 +70,12 @@ class Component(ComponentBase):
""" """
try: try:
successtips = "CPLD Upgrade succeeded!" successtips = "CPLD Upgrade succeeded!"
status, output = subprocess.getstatusoutput("which firmware_upgrade") status, output = getstatusoutput_noshell(["which", "firmware_upgrade"])
if status or len(output) <= 0: if status or len(output) <= 0:
logger.error("no upgrade tool.") logger.error("no upgrade tool.")
return False return False
cmdstr = "%s %s cpld %d cpld"%(output,image_path,self.slot) cmdstr = [output, image_path, "cpld", str(self.slot), "cpld"]
ret, log = subprocess.getstatusoutput(cmdstr) ret, log = getstatusoutput_noshell(cmdstr)
if ret == 0 and successtips in log: if ret == 0 and successtips in log:
return True return True
logger.error("upgrade failed. ret:%d, log:\n%s" % (ret, log)) logger.error("upgrade failed. ret:%d, log:\n%s" % (ret, log))

View File

@ -37,14 +37,14 @@ class PcieUtil(PcieBase):
pciList = [] pciList = []
p1 = "^(\w+):(\w+)\.(\w)\s(.*)\s*\(*.*\)*" p1 = "^(\w+):(\w+)\.(\w)\s(.*)\s*\(*.*\)*"
p2 = "^.*:.*:.*:(\w+)\s*\(*.*\)*" p2 = "^.*:.*:.*:(\w+)\s*\(*.*\)*"
command1 = "sudo lspci" command1 = ["sudo", "lspci"]
command2 = "sudo lspci -n" command2 = ["sudo", "lspci", "-n"]
# run command 1 # run command 1
proc1 = subprocess.Popen(command1, shell=True, universal_newlines=True, stdout=subprocess.PIPE) proc1 = subprocess.Popen(command1, universal_newlines=True, stdout=subprocess.PIPE)
output1 = proc1.stdout.readlines() output1 = proc1.stdout.readlines()
proc1.communicate() proc1.communicate()
# run command 2 # run command 2
proc2 = subprocess.Popen(command2, shell=True, universal_newlines=True, stdout=subprocess.PIPE) proc2 = subprocess.Popen(command2, universal_newlines=True, stdout=subprocess.PIPE)
output2 = proc2.stdout.readlines() output2 = proc2.stdout.readlines()
proc2.communicate() proc2.communicate()

View File

@ -6,9 +6,9 @@
try: try:
import time import time
import subprocess
from sonic_platform_pddf_base.pddf_chassis import PddfChassis from sonic_platform_pddf_base.pddf_chassis import PddfChassis
from rgutil.logutil import Logger from rgutil.logutil import Logger
from sonic_py_common.general import getstatusoutput_noshell
except ImportError as e: except ImportError as e:
raise ImportError(str(e) + "- required module not found") raise ImportError(str(e) + "- required module not found")
@ -30,14 +30,14 @@ class Chassis(PddfChassis):
def __init__(self, pddf_data=None, pddf_plugin_data=None): def __init__(self, pddf_data=None, pddf_plugin_data=None):
PddfChassis.__init__(self, pddf_data, pddf_plugin_data) PddfChassis.__init__(self, pddf_data, pddf_plugin_data)
self.enable_read = "i2cset -f -y 2 0x35 0x2a 0x01" self.enable_read = ["i2cset", "-f", "-y", "2", "0x35", "0x2a", "0x01"]
self.disable_read = "i2cset -f -y 2 0x35 0x2a 0x00" self.disable_read = ["i2cset", "-f", "-y", "2", "0x35", "0x2a", "0x00"]
self.enable_write = "i2cset -f -y 2 0x35 0x2b 0x00" self.enable_write = ["i2cset", "-f", "-y", "2", "0x35", "0x2b", "0x00"]
self.disable_write = "i2cset -f -y 2 0x35 0x2b 0x01" self.disable_write = ["i2cset", "-f", "-y", "2", "0x35", "0x2b", "0x01"]
self.enable_erase = "i2cset -f -y 2 0x35 0x2c 0x01" self.enable_erase = ["i2cset", "-f", "-y", "2", "0x35", "0x2c", "0x01"]
self.disable_erase = "i2cset -f -y 2 0x35 0x2c 0x00" self.disable_erase = ["i2cset", "-f", "-y", "2", "0x35", "0x2c", "0x00"]
self.read_value = "i2cget -f -y 2 0x35 0x25" self.read_value = ["i2cget", "-f", "-y", "2", "0x35", "0x25"]
self.write_value = "i2cset -f -y 2 0x35 0x21 0x0a" self.write_value = ["i2cset", "-f", "-y", "2", "0x35", "0x21", "0x0a"]
def get_reboot_cause(self): def get_reboot_cause(self):
""" """
@ -52,25 +52,25 @@ class Chassis(PddfChassis):
try: try:
is_power_loss = False is_power_loss = False
# enable read # enable read
subprocess.getstatusoutput(self.disable_write) getstatusoutput_noshell(self.disable_write)
subprocess.getstatusoutput(self.enable_read) getstatusoutput_noshell(self.enable_read)
ret, log = subprocess.getstatusoutput(self.read_value) ret, log = getstatusoutput_noshell(self.read_value)
if ret == 0 and "0x0a" in log: if ret == 0 and "0x0a" in log:
is_power_loss = True is_power_loss = True
# erase i2c and e2 # erase i2c and e2
subprocess.getstatusoutput(self.enable_erase) getstatusoutput_noshell(self.enable_erase)
time.sleep(1) time.sleep(1)
subprocess.getstatusoutput(self.disable_erase) getstatusoutput_noshell(self.disable_erase)
# clear data # clear data
subprocess.getstatusoutput(self.enable_write) getstatusoutput_noshell(self.enable_write)
subprocess.getstatusoutput(self.disable_read) getstatusoutput_noshell(self.disable_read)
subprocess.getstatusoutput(self.disable_write) getstatusoutput_noshell(self.disable_write)
subprocess.getstatusoutput(self.enable_read) getstatusoutput_noshell(self.enable_read)
# enable write and set data # enable write and set data
subprocess.getstatusoutput(self.enable_write) getstatusoutput_noshell(self.enable_write)
subprocess.getstatusoutput(self.disable_read) getstatusoutput_noshell(self.disable_read)
subprocess.getstatusoutput(self.write_value) getstatusoutput_noshell(self.write_value)
if is_power_loss: if is_power_loss:
return(self.REBOOT_CAUSE_POWER_LOSS, None) return(self.REBOOT_CAUSE_POWER_LOSS, None)
except Exception as e: except Exception as e:

View File

@ -1,6 +1,6 @@
import os import os
import yaml import yaml
import subprocess
from sonic_py_common import device_info from sonic_py_common import device_info
@ -10,13 +10,13 @@ class Common:
PMON_PLATFORM_PATH = '/usr/share/sonic/platform/' PMON_PLATFORM_PATH = '/usr/share/sonic/platform/'
CONFIG_DIR = 'sonic_platform_config' CONFIG_DIR = 'sonic_platform_config'
HOST_CHK_CMD = "docker > /dev/null 2>&1" HOST_CHK_CMD = ["docker"]
def __init__(self): def __init__(self):
(self.platform, self.hwsku) = device_info.get_platform_and_hwsku() (self.platform, self.hwsku) = device_info.get_platform_and_hwsku()
def is_host(self): def is_host(self):
return os.system(self.HOST_CHK_CMD) == 0 return subprocess.call(self.HOST_CHK_CMD) == 0
def load_json_file(self, path): def load_json_file(self, path):
""" """

View File

@ -8,10 +8,10 @@
######################################################################## ########################################################################
try: try:
import subprocess
from sonic_platform_base.component_base import ComponentBase from sonic_platform_base.component_base import ComponentBase
from sonic_platform.regutil import Reg from sonic_platform.regutil import Reg
from sonic_platform.logger import logger from sonic_platform.logger import logger
from sonic_py_common.general import getstatusoutput_noshell
except ImportError as e: except ImportError as e:
raise ImportError(str(e) + "- required module not found") raise ImportError(str(e) + "- required module not found")
@ -70,16 +70,16 @@ class Component(ComponentBase):
""" """
try: try:
successtips = "CPLD Upgrade succeeded!" successtips = "CPLD Upgrade succeeded!"
status, output = subprocess.getstatusoutput("which firmware_upgrade") status, output = getstatusoutput_noshell(["which", "firmware_upgrade"])
if status or len(output) <= 0: if status or len(output) <= 0:
logger.error("no upgrade tool.") logger.error("no upgrade tool.")
return False return False
cmdstr = "%s %s cpld %d cpld"%(output,image_path,self.slot) cmdstr = [output, image_path, "cpld", str(self.slot), "cpld"]
ret, log = subprocess.getstatusoutput(cmdstr) ret, log = getstatusoutput_noshell(cmdstr)
if ret == 0 and successtips in log: if ret == 0 and successtips in log:
return True return True
logger.error("upgrade failed. ret:%d, log:\n%s" % (ret, log)) logger.error("upgrade failed. ret:%d, log:\n%s" % (ret, log))
except Exception as e: except Exception as e:
logger.error(str(e)) logger.error(str(e))
return False return False

View File

@ -8,9 +8,9 @@
try: try:
import time import time
import subprocess
from sonic_platform_pddf_base.pddf_chassis import PddfChassis from sonic_platform_pddf_base.pddf_chassis import PddfChassis
from rgutil.logutil import Logger from rgutil.logutil import Logger
from sonic_py_common.general import getstatusoutput_noshell
except ImportError as e: except ImportError as e:
raise ImportError(str(e) + "- required module not found") raise ImportError(str(e) + "- required module not found")
@ -32,14 +32,14 @@ class Chassis(PddfChassis):
def __init__(self, pddf_data=None, pddf_plugin_data=None): def __init__(self, pddf_data=None, pddf_plugin_data=None):
PddfChassis.__init__(self, pddf_data, pddf_plugin_data) PddfChassis.__init__(self, pddf_data, pddf_plugin_data)
self.enable_read = "i2cset -f -y 2 0x35 0x2a 0x01" self.enable_read = ["i2cset", "-f", "-y", "2", "0x35", "0x2a", "0x01"]
self.disable_read = "i2cset -f -y 2 0x35 0x2a 0x00" self.disable_read = ["i2cset", "-f", "-y", "2", "0x35", "0x2a", "0x00"]
self.enable_write = "i2cset -f -y 2 0x35 0x2b 0x00" self.enable_write = ["i2cset", "-f", "-y", "2", "0x35", "0x2b", "0x00"]
self.disable_write = "i2cset -f -y 2 0x35 0x2b 0x01" self.disable_write = ["i2cset", "-f", "-y", "2", "0x35", "0x2b", "0x01"]
self.enable_erase = "i2cset -f -y 2 0x35 0x2c 0x01" self.enable_erase = ["i2cset", "-f", "-y", "2", "0x35", "0x2c", "0x01"]
self.disable_erase = "i2cset -f -y 2 0x35 0x2c 0x00" self.disable_erase = ["i2cset", "-f", "-y", "2", "0x35", "0x2c", "0x00"]
self.read_value = "i2cget -f -y 2 0x35 0x25" self.read_value = ["i2cget", "-f", "-y", "2", "0x35", "0x25"]
self.write_value = "i2cset -f -y 2 0x35 0x21 0x0a" self.write_value = ["i2cset", "-f", "-y", "2", "0x35", "0x21", "0x0a"]
def get_reboot_cause(self): def get_reboot_cause(self):
""" """
@ -54,25 +54,25 @@ class Chassis(PddfChassis):
try: try:
is_power_loss = False is_power_loss = False
# enable read # enable read
subprocess.getstatusoutput(self.disable_write) getstatusoutput_noshell(self.disable_write)
subprocess.getstatusoutput(self.enable_read) getstatusoutput_noshell(self.enable_read)
ret, log = subprocess.getstatusoutput(self.read_value) ret, log = getstatusoutput_noshell(self.read_value)
if ret == 0 and "0x0a" in log: if ret == 0 and "0x0a" in log:
is_power_loss = True is_power_loss = True
# erase i2c and e2 # erase i2c and e2
subprocess.getstatusoutput(self.enable_erase) getstatusoutput_noshell(self.enable_erase)
time.sleep(1) time.sleep(1)
subprocess.getstatusoutput(self.disable_erase) getstatusoutput_noshell(self.disable_erase)
# clear data # clear data
subprocess.getstatusoutput(self.enable_write) getstatusoutput_noshell(self.enable_write)
subprocess.getstatusoutput(self.disable_read) getstatusoutput_noshell(self.disable_read)
subprocess.getstatusoutput(self.disable_write) getstatusoutput_noshell(self.disable_write)
subprocess.getstatusoutput(self.enable_read) getstatusoutput_noshell(self.enable_read)
# enable write and set data # enable write and set data
subprocess.getstatusoutput(self.enable_write) getstatusoutput_noshell(self.enable_write)
subprocess.getstatusoutput(self.disable_read) getstatusoutput_noshell(self.disable_read)
subprocess.getstatusoutput(self.write_value) getstatusoutput_noshell(self.write_value)
if is_power_loss: if is_power_loss:
return(self.REBOOT_CAUSE_POWER_LOSS, None) return(self.REBOOT_CAUSE_POWER_LOSS, None)
except Exception as e: except Exception as e:

View File

@ -1,6 +1,6 @@
import os import os
import yaml import yaml
import subprocess
from sonic_py_common import device_info from sonic_py_common import device_info
@ -10,13 +10,13 @@ class Common:
PMON_PLATFORM_PATH = '/usr/share/sonic/platform/' PMON_PLATFORM_PATH = '/usr/share/sonic/platform/'
CONFIG_DIR = 'sonic_platform_config' CONFIG_DIR = 'sonic_platform_config'
HOST_CHK_CMD = "docker > /dev/null 2>&1" HOST_CHK_CMD = ["docker"]
def __init__(self): def __init__(self):
(self.platform, self.hwsku) = device_info.get_platform_and_hwsku() (self.platform, self.hwsku) = device_info.get_platform_and_hwsku()
def is_host(self): def is_host(self):
return os.system(self.HOST_CHK_CMD) == 0 return subprocess.call(self.HOST_CHK_CMD) == 0
def load_json_file(self, path): def load_json_file(self, path):
""" """

View File

@ -37,14 +37,14 @@ class PcieUtil(PcieBase):
pciList = [] pciList = []
p1 = "^(\w+):(\w+)\.(\w)\s(.*)\s*\(*.*\)*" p1 = "^(\w+):(\w+)\.(\w)\s(.*)\s*\(*.*\)*"
p2 = "^.*:.*:.*:(\w+)\s*\(*.*\)*" p2 = "^.*:.*:.*:(\w+)\s*\(*.*\)*"
command1 = "sudo lspci" command1 = ["sudo", "lspci"]
command2 = "sudo lspci -n" command2 = ["sudo", "lspci", "-n"]
# run command 1 # run command 1
proc1 = subprocess.Popen(command1, shell=True, universal_newlines=True, stdout=subprocess.PIPE) proc1 = subprocess.Popen(command1, universal_newlines=True, stdout=subprocess.PIPE)
output1 = proc1.stdout.readlines() output1 = proc1.stdout.readlines()
proc1.communicate() proc1.communicate()
# run command 2 # run command 2
proc2 = subprocess.Popen(command2, shell=True, universal_newlines=True, stdout=subprocess.PIPE) proc2 = subprocess.Popen(command2, universal_newlines=True, stdout=subprocess.PIPE)
output2 = proc2.stdout.readlines() output2 = proc2.stdout.readlines()
proc2.communicate() proc2.communicate()

View File

@ -1,6 +1,6 @@
import os import os
import yaml import yaml
import subprocess
from sonic_py_common import device_info from sonic_py_common import device_info
@ -10,13 +10,13 @@ class Common:
PMON_PLATFORM_PATH = '/usr/share/sonic/platform/' PMON_PLATFORM_PATH = '/usr/share/sonic/platform/'
CONFIG_DIR = 'sonic_platform_config' CONFIG_DIR = 'sonic_platform_config'
HOST_CHK_CMD = "docker > /dev/null 2>&1" HOST_CHK_CMD = ["docker"]
def __init__(self): def __init__(self):
(self.platform, self.hwsku) = device_info.get_platform_and_hwsku() (self.platform, self.hwsku) = device_info.get_platform_and_hwsku()
def is_host(self): def is_host(self):
return os.system(self.HOST_CHK_CMD) == 0 return subprocess.call(self.HOST_CHK_CMD) == 0
def load_json_file(self, path): def load_json_file(self, path):
""" """

View File

@ -8,10 +8,10 @@
######################################################################## ########################################################################
try: try:
import subprocess
from sonic_platform_base.component_base import ComponentBase from sonic_platform_base.component_base import ComponentBase
from sonic_platform.regutil import Reg from sonic_platform.regutil import Reg
from sonic_platform.logger import logger from sonic_platform.logger import logger
from sonic_py_common.general import getstatusoutput_noshell
except ImportError as e: except ImportError as e:
raise ImportError(str(e) + "- required module not found") raise ImportError(str(e) + "- required module not found")
@ -70,16 +70,16 @@ class Component(ComponentBase):
""" """
try: try:
successtips = "CPLD Upgrade succeeded!" successtips = "CPLD Upgrade succeeded!"
status, output = subprocess.getstatusoutput("which firmware_upgrade") status, output = getstatusoutput_noshell(["which", "firmware_upgrade"])
if status or len(output) <= 0: if status or len(output) <= 0:
logger.error("no upgrade tool.") logger.error("no upgrade tool.")
return False return False
cmdstr = "%s %s cpld %d cpld"%(output,image_path,self.slot) cmdstr = [output, image_path, "cpld", str(self.slot), "cpld"]
ret, log = subprocess.getstatusoutput(cmdstr) ret, log = getstatusoutput_noshell(cmdstr)
if ret == 0 and successtips in log: if ret == 0 and successtips in log:
return True return True
logger.error("upgrade failed. ret:%d, log:\n%s" % (ret, log)) logger.error("upgrade failed. ret:%d, log:\n%s" % (ret, log))
except Exception as e: except Exception as e:
logger.error(str(e)) logger.error(str(e))
return False return False