[ruijie] Replace os.system and remove subprocess with shell=True (#12107)

Signed-off-by: maipbui <maibui@microsoft.com>
Dependency: [https://github.com/sonic-net/sonic-buildimage/pull/12065](https://github.com/sonic-net/sonic-buildimage/pull/12065)
#### Why I did it
1. `getstatusoutput` is used without a static string and it uses `shell=True`
2. `subprocess()` - when using with `shell=True` is dangerous. Using subprocess function without a static string can lead to command injection.
3. `os` - not secure against maliciously constructed input and dangerous if used to evaluate dynamic content.
#### How I did it
1. use `getstatusoutput` without shell=True
2. `subprocess()` - use `shell=False` instead. use an array string. Ref: [https://semgrep.dev/docs/cheat-sheets/python-command-injection/#mitigation](https://semgrep.dev/docs/cheat-sheets/python-command-injection/#mitigation)
3. `os` - use with `subprocess`
This commit is contained in:
Mai Bui 2022-11-28 12:43:43 -05:00 committed by GitHub
parent d82e1321bc
commit 35c4e9912d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
8 changed files with 151 additions and 152 deletions

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

@ -10,13 +10,13 @@
try: try:
import time import time
import subprocess
from sonic_platform_base.chassis_base import ChassisBase from sonic_platform_base.chassis_base import ChassisBase
from sonic_platform.common import Common from sonic_platform.common import Common
from sonic_platform.sfp import Sfp from sonic_platform.sfp import Sfp
from sonic_platform.sfp import PORT_START from sonic_platform.sfp import PORT_START
from sonic_platform.sfp import PORTS_IN_BLOCK from sonic_platform.sfp import PORTS_IN_BLOCK
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")
@ -36,17 +36,17 @@ class Chassis(ChassisBase):
self.SFP_STATUS_INSERTED = "1" self.SFP_STATUS_INSERTED = "1"
self.SFP_STATUS_REMOVED = "0" self.SFP_STATUS_REMOVED = "0"
self.port_dict = {} self.port_dict = {}
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"]
self.set_sys_led_cmd = "i2cset -f -y 2 0x33 0xb2 " self.set_sys_led_cmd = ["i2cset", "-f", "-y", "2", "0x33", "0xb2"]
self.get_sys_led_cmd = "i2cget -f -y 2 0x33 0xb2" self.get_sys_led_cmd = ["i2cget", "-f", "-y", "2", "0x33", "0xb2"]
self.led_status = "red" self.led_status = "red"
# Initialize SFP list # Initialize SFP list
# sfp.py will read eeprom contents and retrive the eeprom data. # sfp.py will read eeprom contents and retrive the eeprom data.
# It will also provide support sfp controls like reset and setting # It will also provide support sfp controls like reset and setting
@ -210,25 +210,25 @@ class Chassis(ChassisBase):
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:
@ -417,7 +417,8 @@ class Chassis(ChassisBase):
if regval is None: if regval is None:
print("Invaild color input.") print("Invaild color input.")
return False return False
ret , log = subprocess.getstatusoutput(self.set_sys_led_cmd + regval) cmd = self.set_sys_led_cmd + [regval]
ret, log = getstatusoutput_noshell(cmd)
if ret != 0: if ret != 0:
print("Cannot execute %s" % self.set_sys_led_cmd + regval) print("Cannot execute %s" % self.set_sys_led_cmd + regval)
return False return False
@ -431,7 +432,7 @@ class Chassis(ChassisBase):
A string, one of the valid LED color strings which could be vendor A string, one of the valid LED color strings which could be vendor
specified. specified.
""" """
ret , log = subprocess.getstatusoutput(self.get_sys_led_cmd) ret , log = getstatusoutput_noshell(self.get_sys_led_cmd)
if ret != 0: if ret != 0:
print("Cannot execute %s" % self.get_sys_led_cmd) print("Cannot execute %s" % self.get_sys_led_cmd)
return False return False

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", 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

@ -6,7 +6,6 @@
# #
####################################################### #######################################################
import subprocess
import time import time
import glob import glob
import re import re
@ -14,6 +13,7 @@ import re
from rjutil.smbus import SMBus from rjutil.smbus import SMBus
import time import time
from functools import wraps from functools import wraps
from sonic_py_common.general import getstatusoutput_noshell
def retry(maxretry =6, delay = 0.01): def retry(maxretry =6, delay = 0.01):
@ -80,13 +80,13 @@ class osutil(object):
@staticmethod @staticmethod
def command(cmdstr): def command(cmdstr):
retcode, output = subprocess.getstatusoutput(cmdstr) retcode, output = getstatusoutput_noshell(cmdstr)
return retcode, output return retcode, output
@staticmethod @staticmethod
def geti2cword_i2ctool(bus, addr, offset): def geti2cword_i2ctool(bus, addr, offset):
command_line = "i2cget -f -y %d 0x%02x 0x%02x wp" % (bus, addr, offset) command_line = ["i2cget", "-f", "-y", str(bus), "0x%02x"%addr, "0x%02x"%offset, "wp"]
retrytime = 6 retrytime = 6
ret_t = "" ret_t = ""
for i in range(retrytime): for i in range(retrytime):
@ -99,7 +99,7 @@ class osutil(object):
@staticmethod @staticmethod
def seti2cword_i2ctool(bus, addr, offset, val): def seti2cword_i2ctool(bus, addr, offset, val):
command_line = "i2cset -f -y %d 0x%02x 0x%0x 0x%04x wp" % (bus, addr, offset, val) command_line = ["i2cset", "-f", "-y", str(bus), "0x%02x"%addr, "0x%0x"%offset, "0x%04x"%val, "wp"]
retrytime = 6 retrytime = 6
ret_t = "" ret_t = ""
for i in range(retrytime): for i in range(retrytime):
@ -111,7 +111,7 @@ class osutil(object):
@staticmethod @staticmethod
def rji2cget_i2ctool(bus, devno, address): def rji2cget_i2ctool(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):
@ -123,8 +123,7 @@ class osutil(object):
@staticmethod @staticmethod
def rji2cset_i2ctool(bus, devno, address, byte): def rji2cset_i2ctool(bus, devno, address, byte):
command_line = "i2cset -f -y %d 0x%02x 0x%02x 0x%02x" % ( command_line = ["i2cset", "-f", "-y", str(bus), "0x%02x"%devno, "0x%02x"%address, "0x%02x"%byte]
bus, devno, address, byte)
retrytime = 6 retrytime = 6
ret_t = "" ret_t = ""
for i in range(retrytime): for i in range(retrytime):
@ -166,7 +165,7 @@ class osutil(object):
@staticmethod @staticmethod
def getdevmem(addr, digit, mask): def getdevmem(addr, digit, mask):
command_line = "devmem 0x%02x %d" %(addr, digit) command_line = ["devmem", "0x%02x"%addr, str(digit)]
retrytime = 6 retrytime = 6
ret_t = "" ret_t = ""
for i in range(retrytime): for i in range(retrytime):
@ -179,13 +178,13 @@ class osutil(object):
@staticmethod @staticmethod
def rj_os_system(cmd): def rj_os_system(cmd):
status, output = subprocess.getstatusoutput(cmd) status, output = getstatusoutput_noshell(cmd)
return status, output return status, output
@staticmethod @staticmethod
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 = osutil.rj_os_system(cmd) ret, result = osutil.rj_os_system(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:
@ -203,8 +202,8 @@ class osutil(object):
result = {} result = {}
#waitForDocker() #waitForDocker()
#need to exec twice #need to exec twice
osutil.rj_os_system("bcmcmd -t 1 \"show temp\" < /dev/null") osutil.rj_os_system(["bcmcmd", "-t", "1", "show temp"])
ret, log = osutil.rj_os_system("bcmcmd -t 1 \"show temp\" < /dev/null") ret, log = osutil.rj_os_system(["bcmcmd", "-t", "1", "show temp"])
if ret: if ret:
return False, result return False, result
else: else:

View File

@ -6,7 +6,7 @@ import os
import subprocess import subprocess
import time import time
from ruijieconfig import GLOBALCONFIG, GLOBALINITPARAM, GLOBALINITCOMMAND, MAC_LED_RESET, STARTMODULE, i2ccheck_params from ruijieconfig import GLOBALCONFIG, GLOBALINITPARAM, GLOBALINITCOMMAND, MAC_LED_RESET, STARTMODULE, i2ccheck_params
from sonic_py_common.general import getstatusoutput_noshell, getstatusoutput_noshell_pipe
from ruijieutil import rjpciwr from ruijieutil import rjpciwr
CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help']) CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])
@ -46,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
@ -70,61 +70,59 @@ def i2c_getPid(name):
return ret return ret
def startAvscontrol(): def startAvscontrol():
cmd = "nohup avscontrol.py start >/dev/null 2>&1 &" cmd = ["avscontrol.py", "start"]
rets = i2c_getPid("avscontrol.py") rets = i2c_getPid("avscontrol.py")
if len(rets) == 0: if len(rets) == 0:
os.system(cmd) subprocess.Popen(cmd)
def startFanctrol(): def startFanctrol():
if STARTMODULE['fancontrol'] == 1: if STARTMODULE['fancontrol'] == 1:
cmd = "nohup fancontrol.py start >/dev/null 2>&1 &" cmd = ["fancontrol.py", "start"]
rets = i2c_getPid("fancontrol.py") rets = i2c_getPid("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 = i2c_getPid("hal_fanctrl.py") rets = i2c_getPid("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 = i2c_getPid("hal_ledctrl.py") rets = i2c_getPid("hal_ledctrl.py")
if len(rets) == 0: if len(rets) == 0:
os.system(cmd) subprocess.Popen(cmd)
def startDevmonitor(): def startDevmonitor():
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 = i2c_getPid("dev_monitor.py") rets = i2c_getPid("dev_monitor.py")
if len(rets) == 0: if len(rets) == 0:
os.system(cmd) subprocess.Popen(cmd)
def startSlotmonitor(): def startSlotmonitor():
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 = i2c_getPid("slot_monitor.py") rets = i2c_getPid("slot_monitor.py")
if len(rets) == 0: if len(rets) == 0:
os.system(cmd) subprocess.Popen(cmd)
def stopFanctrol(): def stopFanctrol():
u'''disable fan timer service''' u'''disable fan timer service'''
if STARTMODULE['fancontrol'] == 1: if STARTMODULE['fancontrol'] == 1:
rets = i2c_getPid("fancontrol.py") # rets = i2c_getPid("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 = i2c_getPid("hal_ledctrl.py") rets = i2c_getPid("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
@ -133,8 +131,8 @@ def stopDevmonitor():
if STARTMODULE.get('dev_monitor',0) == 1: if STARTMODULE.get('dev_monitor',0) == 1:
rets = i2c_getPid("dev_monitor.py") # rets = i2c_getPid("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 stopSlotmonitor(): def stopSlotmonitor():
@ -142,15 +140,16 @@ def stopSlotmonitor():
if STARTMODULE.get('slot_monitor',0) == 1: if STARTMODULE.get('slot_monitor',0) == 1:
rets = i2c_getPid("slot_monitor.py") # rets = i2c_getPid("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 removeDev(bus, loc): def removeDev(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) file = "/sys/bus/i2c/devices/i2c-%d/delete_device" % bus
with open(file, 'w') as f:
f.write('0x%02x\n'%str(bus))
def addDev(name, bus, loc): def addDev(name, bus, loc):
if name == "lm75": if name == "lm75":
@ -163,10 +162,11 @@ def addDev(name, bus, loc):
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) == False:
os.system(cmd) file = "/sys/bus/i2c/devices/i2c-%d/new_device" % bus
with open(file, 'w') as f:
f.write('%s 0x%02x\n' % (name, loc))
def removedevs(): def removedevs():
devs = GLOBALCONFIG["DEVS"] devs = GLOBALCONFIG["DEVS"]
@ -179,8 +179,7 @@ def adddevs():
addDev(devs[dev]["name"], devs[dev]["bus"] , devs[dev]["loc"]) addDev(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
@ -190,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 checksignaldriver(name) != True:
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

@ -4,6 +4,7 @@ import click
import os import os
import time import time
import syslog import syslog
import subprocess
from ruijieconfig import MONITOR_CONST, FANCTROLDEBUG, MONITOR_FANS_LED, DEV_LEDS, MONITOR_PSU_STATUS, \ from ruijieconfig import MONITOR_CONST, FANCTROLDEBUG, MONITOR_FANS_LED, DEV_LEDS, MONITOR_PSU_STATUS, \
MONITOR_SYS_PSU_LED, MONITOR_DEV_STATUS, MONITOR_FAN_STATUS, MONITOR_DEV_STATUS_DECODE, \ MONITOR_SYS_PSU_LED, MONITOR_DEV_STATUS, MONITOR_FAN_STATUS, MONITOR_DEV_STATUS_DECODE, \
MONITOR_SYS_FAN_LED, MONITOR_SYS_LED, fanloc MONITOR_SYS_FAN_LED, MONITOR_SYS_LED, fanloc
@ -766,7 +767,7 @@ class FanControl(object):
self.fanSpeedSetMax() # fan full speed self.fanSpeedSetMax() # 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"])
fanwarningdebuglog(DEBUG_FANCONTROL,"crit次数:%d" % self.critnum) fanwarningdebuglog(DEBUG_FANCONTROL,"crit次数:%d" % self.critnum)
else: else:
self.critnum = 0 self.critnum = 0

View File

@ -11,7 +11,6 @@
import sys import sys
import os import os
import re import re
import subprocess
import syslog import syslog
import time import time
import binascii import binascii
@ -20,6 +19,7 @@ import termios
import threading import threading
import click import click
import mmap import mmap
from sonic_py_common.general import getstatusoutput_noshell, getstatusoutput_noshell_pipe
from ruijieconfig import rg_eeprom, FRULISTS, MAC_DEFAULT_PARAM, MAC_AVS_PARAM, FANS_DEF, \ from ruijieconfig import rg_eeprom, FRULISTS, MAC_DEFAULT_PARAM, MAC_AVS_PARAM, FANS_DEF, \
FAN_PROTECT, E2_LOC, E2_PROTECT, RUIJIE_SERVICE_TAG, RUIJIE_DIAG_VERSION, \ FAN_PROTECT, E2_LOC, E2_PROTECT, RUIJIE_SERVICE_TAG, RUIJIE_DIAG_VERSION, \
STARTMODULE, RUIJIE_CARDID, RUIJIE_PRODUCTNAME, RUIJIE_PART_NUMBER, \ STARTMODULE, RUIJIE_CARDID, RUIJIE_PRODUCTNAME, RUIJIE_PART_NUMBER, \
@ -538,8 +538,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 = rj_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
@ -632,8 +632,8 @@ def getMacTemp():
result = {} result = {}
#waitForDocker() #waitForDocker()
# exec twice, get the second result # exec twice, get the second result
rj_os_system("bcmcmd -t 1 \"show temp\" < /dev/null") getstatusoutput_noshell(["bcmcmd", "-t", "1", "show temp"])
ret, log = rj_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:
@ -689,21 +689,21 @@ def getMacTemp_sysfs(mactempconf):
def restartDockerService(force=False): def restartDockerService(force=False):
container_name = ["database","snmp","syncd","swss","dhcp_relay","radv","teamd","pmon"] container_name = ["database","snmp","syncd","swss","dhcp_relay","radv","teamd","pmon"]
ret, status = rj_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):
rj_os_system("docker restart %s"%tmpname) getstatusoutput_noshell(["docker", "restart", tmpname])
else: else:
rj_os_system("systemctl restart %s"%tmpname) getstatusoutput_noshell(["systemctl", "restart", tmpname])
def waitForDhcp(timeout): def waitForDhcp(timeout):
time_cnt = 0 time_cnt = 0
while True: while True:
try: try:
ret, status = rj_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:
@ -839,8 +839,10 @@ 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) == 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 = rj_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):
@ -848,23 +850,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(' '.join(ifconfigcmd))
ret, status = rj_os_system(ifconfigcmd) ret, status = getstatusoutput_noshell(ifconfigcmd)
if ret: if ret:
raise SETMACException("software set Internet cardMAC error") raise SETMACException("software set Internet cardMAC error")
index = 0 index = 0
for item in macs: for item in macs:
cmd = "ethtool -E %s magic %s offset %d value 0x%s" % ( cmd = ["ethtool", "-E", eht, "magic", magic, "offset", str(index), "value", "0x"+item]
eth, magic, index, item)
log_debug(cmd) log_debug(cmd)
index += 1 index += 1
ret, log = rj_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 = rj_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(" ")
@ -979,11 +980,11 @@ def generate_ext(cardid):
def rji2cget(bus, devno, address): def rji2cget(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"%str(devno), "0x%02x"%str(address)]
retrytime = 6 retrytime = 6
ret_t = "" ret_t = ""
for i in range(retrytime): for i in range(retrytime):
ret, ret_t = rj_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)
@ -991,12 +992,11 @@ def rji2cget(bus, devno, address):
def rji2cset(bus, devno, address, byte): def rji2cset(bus, devno, address, byte):
command_line = "i2cset -f -y %d 0x%02x 0x%02x 0x%02x" % ( command_line = ["i2cset", "-f", "-y", str(bus), "0x%02x"%str(devno), "0x%02x"%str(address), "0x%02x"%str(byte)]
bus, devno, address, byte)
retrytime = 6 retrytime = 6
ret_t = "" ret_t = ""
for i in range(retrytime): for i in range(retrytime):
ret, ret_t = rj_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
@ -1033,31 +1033,30 @@ def rjpciwr(pcibus , slot ,fn, bar, offset, data):
data.close() data.close()
def rjsysset(location, value): def rjsysset(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 = rj_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 rji2cgetWord(bus, devno, address): def rji2cgetWord(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"%str(devno), "0x%02x"%str(address), "w"]
retrytime = 3 retrytime = 3
ret_t = "" ret_t = ""
for i in range(retrytime): for i in range(retrytime):
ret, ret_t = rj_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 rji2csetWord(bus, devno, address, byte): def rji2csetWord(bus, devno, address, byte):
command_line = "i2cset -f -y %d 0x%02x 0x%02x 0x%x w" % ( command_line = ["i2cset", "-f", "-y", str(bus), "0x%02x"%str(devno), "0x%02x"%str(address), "0x%x"%str(byte), "w"]
bus, devno, address, byte) getstatusoutput_noshell(command_line)
rj_os_system(command_line)
def fan_setmac(): def fan_setmac():
@ -1264,14 +1263,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 ") getstatusoutput_noshell(["rmmod", "at24"])
os.system("modprobe at24 ") getstatusoutput_noshell(["modprobe", "at24"])
os.system("rm -f /var/cache/sonic/decode-syseeprom/syseeprom_cache") getstatusoutput_noshell(["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(rj_os_system(cmd)) cmd2 = ["grep", "HWaddr"]
print(getstatusoutput_noshell_pipe(cmd1, cmd2))
def getonieversion(): def getonieversion():
if not os.path.isfile('/host/machine.conf'): if not os.path.isfile('/host/machine.conf'):
@ -1348,12 +1348,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))
rj_os_system(cmdinit) getstatusoutput_noshell(cmdinit)
ret, status = rj_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
@ -1393,11 +1393,11 @@ def closeProtocol():
log_info("disable LLDP") log_info("disable LLDP")
sys.stdout.write(".") sys.stdout.write(".")
sys.stdout.flush() sys.stdout.flush()
rj_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()
rj_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()
@ -1420,8 +1420,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")
rj_os_system("sync") getstatusoutput_noshell(["sync"])
rj_os_system("reboot") getstatusoutput_noshell(["reboot"])
########################################################################## ##########################################################################
# receives a character setting # receives a character setting
@ -1604,25 +1604,22 @@ def getCardId():
return item.get('value',None) return item.get('value',None)
return None return None
# ====================================
# execute shell command
# ====================================
def rj_os_system(cmd):
status, output = subprocess.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 = rj_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[0].rstrip('\n')]
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 = rj_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")
@ -1642,15 +1639,16 @@ def getsysmeminfo():
# return various arrays # return various arrays
########################################### ###########################################
def getsysmeminfo_detail(): def getsysmeminfo_detail():
ret, log = rj_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[0].rstrip('\n')] + ["-t", "17"]
cmd2 = ["grep", "-A21", "Memory Device"] # 17
# get total number # get total number
ret1, log1 = rj_os_system(cmd) ret1, log1 = getstatusoutput_noshell_pipe(cmd1, cmd2)
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][%s]" % (cmd1, cmd2)
result_t = log1.split("--") result_t = log1.split("--")
mem_rets = [] mem_rets = []
for item in result_t: for item in result_t:
@ -1669,13 +1667,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 = rj_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[0].rstrip('\n')] + ["-t", str(type_t)]
# get total number # get total number
ret1, log1 = rj_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")
@ -1742,11 +1740,12 @@ def getusbinfo():
return False, "Err" return False, "Err"
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 = rj_os_system(cmd) 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][%s]" % (cmd1, cmd2)
result_t = log1.split("--") result_t = log1.split("--")
mem_rets = [] mem_rets = []
for item in result_t: for item in result_t: