diff --git a/device/juniper/x86_64-juniper_qfx5200-r0/plugins/qfx5200_eeprom_data.py b/device/juniper/x86_64-juniper_qfx5200-r0/plugins/qfx5200_eeprom_data.py index ea53f11e69..e5d51d302f 100644 --- a/device/juniper/x86_64-juniper_qfx5200-r0/plugins/qfx5200_eeprom_data.py +++ b/device/juniper/x86_64-juniper_qfx5200-r0/plugins/qfx5200_eeprom_data.py @@ -34,13 +34,9 @@ import binascii import os -import sys +import subprocess from sonic_eeprom import eeprom_tlvinfo - -if sys.version_info[0] < 3: - import commands -else: - import subprocess as commands +from sonic_py_common.general import getstatusoutput_noshell def fantype_detect(): @@ -56,9 +52,7 @@ def fantype_detect(): for filename in os.listdir(refpgaTMC_path): if filename.endswith('_type'): fantype_path = os.path.join(refpgaTMC_path, filename) - cat_string = "cat " - fantype_string = cat_string + fantype_path - status, fan_type = commands.getstatusoutput(fantype_string) + status, fan_type = getstatusoutput_noshell(['cat', fantype_path]) if ((fan_type == AFO) or (fan_type == AFI)): return fan_type else: @@ -176,17 +170,21 @@ def main(): eeprom_file.write("Main board eeprom (0x57)\r\n") eeprom_file.write("===============================\r\n") - MainEepromCreate = 'sudo echo 24c02 0x57 > /sys/bus/i2c/devices/i2c-0/new_device' + MainEepromCreate = '24c02 0x57' + out_file = '/sys/bus/i2c/devices/i2c-0/new_device' # Write the contents of Main Board EEPROM to file try: - os.system(MainEepromCreate) + with open(out_file, 'w') as file: + file.write(MainEepromCreate) except OSError: print('Error: Execution of "%s" failed', MainEepromCreate) return False - MainEepromFileCmd = 'cat /sys/bus/i2c/devices/i2c-0/0-0057/eeprom > /etc/init.d/MainEeprom_qfx5200_ascii' + MainEepromFileCmd = ['cat', '/sys/bus/i2c/devices/i2c-0/0-0057/eeprom'] + out_file = '/etc/init.d/MainEeprom_qfx5200_ascii' try: - os.system(MainEepromFileCmd) + with open(out_file, 'w') as file: + subprocess.call(MainEepromFileCmd, universal_newlines=True, stdout=file) except OSError: print('Error: Execution of "%s" failed', MainEepromFileCmd) return False diff --git a/device/juniper/x86_64-juniper_qfx5210-r0/plugins/qfx5210_eeprom_data.py b/device/juniper/x86_64-juniper_qfx5210-r0/plugins/qfx5210_eeprom_data.py index b0aef43ba2..347e2472ff 100644 --- a/device/juniper/x86_64-juniper_qfx5210-r0/plugins/qfx5210_eeprom_data.py +++ b/device/juniper/x86_64-juniper_qfx5210-r0/plugins/qfx5210_eeprom_data.py @@ -32,8 +32,8 @@ # components is subject to the terms and conditions of the respective license # as noted in the Third-Party source code file. -import os import binascii +import subprocess from sonic_eeprom import eeprom_tlvinfo @@ -81,10 +81,12 @@ def main(): eeprom_file.write("Vendor Name=%s\r\n" % eeprom_qfx5210.vendor_name_str()) eeprom_file.write("Manufacture Name=%s\r\n" % eeprom_qfx5210.manufacture_name_str()) - CPUeepromFileCmd = 'cat /sys/devices/pci0000:00/0000:00:1f.3/i2c-0/0-0056/eeprom > /etc/init.d/eeprom_qfx5210_ascii' + CPUeepromFileCmd = ['cat', '/sys/devices/pci0000:00/0000:00:1f.3/i2c-0/0-0056/eeprom'] # Write the contents of CPU EEPROM to file + out_file = '/etc/init.d/eeprom_qfx5210_ascii' try: - os.system(CPUeepromFileCmd) + with open(out_file, 'w') as file: + subprocess.call(CPUeepromFileCmd, universal_newlines=True, stdout=file) except OSError: print('Error: Execution of "%s" failed', CPUeepromFileCmd) return False diff --git a/platform/broadcom/sonic-platform-modules-juniper/qfx5200/utils/juniper_qfx5200_monitor.py b/platform/broadcom/sonic-platform-modules-juniper/qfx5200/utils/juniper_qfx5200_monitor.py index dc47f10493..6546fff0cf 100755 --- a/platform/broadcom/sonic-platform-modules-juniper/qfx5200/utils/juniper_qfx5200_monitor.py +++ b/platform/broadcom/sonic-platform-modules-juniper/qfx5200/utils/juniper_qfx5200_monitor.py @@ -34,7 +34,6 @@ try: import os - import commands import subprocess import logging import logging.config @@ -42,6 +41,7 @@ try: import time import glob import re + from sonic_py_common.general import getstatusoutput_noshell except ImportError as e: raise ImportError('%s - required module not found' % str(e)) @@ -172,8 +172,8 @@ class QFX5200_FanUtil(object): pwm_value = 0 pwm_value1 = 0 device_path = self._pwm_input_path_mapping[x] - cmd = ("sudo cat %s" %(device_path)) - status, pwm_value = commands.getstatusoutput(cmd) + cmd = ["sudo", "cat", device_path] + status, pwm_value = getstatusoutput_noshell(cmd) pwm_value1 = int(pwm_value) time.sleep(0.25) if int(pwm_value1) > 0: @@ -181,6 +181,10 @@ class QFX5200_FanUtil(object): break return int(ret_value) + + def write_file(self, text, file): + with open(file, 'w') as f: + f.write(text + '\n') def set_fan_dutycycle(self, val): fan_speed = {35: 86, 55: 139, 75: 192, 90: 230,100: 255} @@ -188,8 +192,7 @@ class QFX5200_FanUtil(object): device_path = self._pwm_input_path_mapping[x] pwm_value = fan_speed.get(val) pwm_value1 = str(pwm_value) - cmd = ("sudo echo %s > %s" %(pwm_value1,device_path)) - os.system(cmd) + self.write_file(pwm_value1,device_path) time.sleep(0.25) logging.debug('Setting PWM value: %s to all fans', pwm_value1) return True @@ -198,8 +201,8 @@ class QFX5200_FanUtil(object): pwm_str = '' for x in range(self.PWMINPUT_NUM): device_path = self._pwm_input_path_mapping[x] - cmd = ("sudo cat %s" %(device_path)) - status, pwm_value = commands.getstatusoutput(cmd) + cmd = ["sudo", "cat", device_path] + status, pwm_value = getstatusoutput_noshell(cmd) pwm_str += pwm_value if (x != self.PWMINPUT_NUM -1): pwm_str += ', ' @@ -495,8 +498,8 @@ class QFX5200_ThermalUtil(object): else: proc = subprocess.Popen("bcmcmd \"show temp\" | grep \"maximum peak temperature\" | awk '{ print $5 }' > /var/log/asic_value 2>&1 & ",shell=True) time.sleep(2) - cmd = "kill -9 %s"%(proc.pid) - commands.getstatusoutput(cmd) + cmd = ["kill", "-9", proc.pid] + getstatusoutput_noshell(cmd) if os.stat("/var/log/asic_value").st_size == 0: value = PrevASICValue @@ -568,7 +571,7 @@ class QFX5200_ThermalUtil(object): or SensorFlag[8][11] or SensorFlag[9][11] or SensorFlag[10][11] or SensorFlag[11][11]): logging.debug('Fire Threshold reached: System is going to shutdown now') - os.system("echo 'CRITICAL: Fire Threshold reached: System is going to shutdown now' > /dev/console") + self.write_file('CRITICAL: Fire Threshold reached: System is going to shutdown now', "/dev/console") logging.debug('Executing poweroff command') @@ -583,8 +586,8 @@ class QFX5200_ThermalUtil(object): monitorlog_file.close() - cmd = "poweroff" - os.system(cmd) + cmd = ["poweroff"] + subprocess.call(cmd) # CHECK IF ANY TEMPERATURE SENSORS is running at RED warning , IF YES, SET THE ALARM LED TO 'RED' elif (SensorFlag[0][10] or SensorFlag[1][10] or SensorFlag[2][10] or SensorFlag[3][10] or SensorFlag[4][10] or SensorFlag[5][10] or SensorFlag[6][10] or SensorFlag[7][10] @@ -878,8 +881,7 @@ class device_monitor(object): pwm_value = fan_speed.get(val) pwm_value1 = str(pwm_value) time.sleep(0.25) - cmd = ("sudo echo %s > %s" %(pwm_value1,device_path)) - os.system(cmd) + self.write_file(pwm_value1, device_path) logging.debug('Setting Default PWM value: 86 to all fans') return True @@ -888,8 +890,8 @@ class device_monitor(object): pwm_str = '' for x in range(self.PWMINPUT_NUM): device_path = self._pwm_input_path_mapping[x] - cmd = ("sudo cat %s" %(device_path)) - status, pwm_value = commands.getstatusoutput(cmd) + cmd = ["sudo", "cat", device_path] + status, pwm_value = getstatusoutput_noshell(cmd) pwm_str += pwm_value if (x != self.PWMINPUT_NUM -1): pwm_str += ', ' diff --git a/platform/broadcom/sonic-platform-modules-juniper/qfx5200/utils/juniper_qfx5200_util.py b/platform/broadcom/sonic-platform-modules-juniper/qfx5200/utils/juniper_qfx5200_util.py index 2e6171d991..7b265685c3 100755 --- a/platform/broadcom/sonic-platform-modules-juniper/qfx5200/utils/juniper_qfx5200_util.py +++ b/platform/broadcom/sonic-platform-modules-juniper/qfx5200/utils/juniper_qfx5200_util.py @@ -23,6 +23,8 @@ import commands import sys import logging import time +import subprocess +from sonic_py_common.general import getstatusoutput_noshell PROJECT_NAME = 'QFX5200-32C' verbose = False @@ -30,8 +32,8 @@ DEBUG = False FORCE = 0 if DEBUG == True: - print sys.argv[0] - print 'ARGV :', sys.argv[1:] + print(sys.argv[0]) + print('ARGV :', sys.argv[1:]) i2c_prefix = '/sys/bus/i2c/devices/' @@ -70,7 +72,7 @@ mknod =[ def my_log(txt): if DEBUG == True: - print txt + print(txt) return def log_os_system(cmd, show): @@ -83,6 +85,10 @@ def log_os_system(cmd, show): if show: print('Failed :'+cmd) return status, output + +def write_file(text, file): + with open(file, 'w') as f: + f.write(text + '\n') def driver_install(): global FORCE @@ -106,7 +112,7 @@ def device_install(): for i in range(0,len(mknod)): status, output = log_os_system(mknod[i], 1) if status: - print output + print(output) if FORCE == 0: return status @@ -123,7 +129,7 @@ def do_install(): if FORCE == 0: return status else: - print PROJECT_NAME.upper()+" devices detected...." + print(PROJECT_NAME.upper()+" devices detected....") return def main(): @@ -139,49 +145,50 @@ def main(): # Enabling REFPGA - EnableREFFGACmd = 'busybox devmem 0xFED50011 8 0x53' + EnableREFFGACmd = ['busybox', 'devmem', '0xFED50011', '8', '0x53'] try: - os.system(EnableREFFGACmd) + subprocess.call(EnableREFFGACmd) except OSError: - print 'Error: Execution of "%s" failed', EnableREFFGACmd + print('Error: Execution of "%s" failed', EnableREFFGACmd) return False time.sleep(2) # Create CPU Board EEPROM device - CreateEEPROMdeviceCmd = 'sudo echo 24c02 0x51 > /sys/bus/i2c/devices/i2c-0/new_device' + CreateEEPROMdeviceCmd = '24c02 0x51' + file = '/sys/bus/i2c/devices/i2c-0/new_device' try: - os.system(CreateEEPROMdeviceCmd) + write_file(CreateEEPROMdeviceCmd, file) except OSError: - print 'Error: Execution of "%s" failed', CreateEEPROMdeviceCmd + print('Error: Execution of "%s" failed', CreateEEPROMdeviceCmd) return False time.sleep(1) #Retrieve the Base MAC Address from EEPROM - status, macAddress = commands.getstatusoutput("decode-syseeprom -m 0x24") + status, macAddress = getstatusoutput_noshell(["decode-syseeprom", "-m", "0x24"]) if status: - print 'Error: Could not retrieve BASE MAC Address from EEPROM' + print('Error: Could not retrieve BASE MAC Address from EEPROM') return False #Make eth0 interface down - status, eth0Down = commands.getstatusoutput("ifconfig eth0 down") + status, eth0Down = getstatusoutput_noshell(["ifconfig", "eth0", "down"]) if status: - print 'Error: Could not make eth0 interface down' + print('Error: Could not make eth0 interface down') return False #Assign BASE MAC ADDRESS retieved from CPU board EEPROM to eth0 interface - mac_address_prog = "ifconfig eth0 hw ether " + str(macAddress) + mac_address_prog = ["ifconfig", "eth0", "hw", "ether", str(macAddress)] - status, MACAddressProg = commands.getstatusoutput(mac_address_prog) + status, MACAddressProg = getstatusoutput_noshell(mac_address_prog) if status: - print 'Error: Could not set up "macAddress" for eth0 interface' + print('Error: Could not set up "macAddress" for eth0 interface') return False #Make eth0 interface up - status, eth0UP = commands.getstatusoutput("ifconfig eth0 up") + status, eth0UP = getstatusoutput_noshell(["ifconfig", "eth0", "up"]) if status: - print 'Error: Could not make eth0 interface up' + print('Error: Could not make eth0 interface up') return False # Juniper QFX5200 platform drivers install @@ -189,20 +196,20 @@ def main(): time.sleep(2) # Juniper SFP Intialization - JuniperSFPInitCmd = 'python /usr/share/sonic/device/x86_64-juniper_qfx5200-r0/plugins/qfx5200_sfp_init.py' + JuniperSFPInitCmd = ['python', '/usr/share/sonic/device/x86_64-juniper_qfx5200-r0/plugins/qfx5200_sfp_init.py'] try: - os.system(JuniperSFPInitCmd) + subprocess.call(JuniperSFPInitCmd) except OSError: - print 'Error: Execution of "%s" failed', JuniperSFPInitCmd + print('Error: Execution of "%s" failed', JuniperSFPInitCmd) return False time.sleep(1) # Invoking the script which retrieves the data from CPU Board and Main Board EEPROM and storing in file - EEPROMDataCmd = 'python /usr/share/sonic/device/x86_64-juniper_qfx5200-r0/plugins/qfx5200_eeprom_data.py' + EEPROMDataCmd = ['python', '/usr/share/sonic/device/x86_64-juniper_qfx5200-r0/plugins/qfx5200_eeprom_data.py'] try: - os.system(EEPROMDataCmd) + subprocess.call(EEPROMDataCmd) except OSError: - print 'Error: Execution of "%s" failed', EEPROMDataCmd + print('Error: Execution of "%s" failed', EEPROMDataCmd) return False for x in range(PWMINPUT_NUM): @@ -218,16 +225,16 @@ def main(): hwmon_dir) device_path = pwm_input_path_mapping[x] time.sleep(1) - cmd = ("sudo echo 22500 > %s" %device_path) - os.system(cmd) + cmd = "22500" + write_file(cmd, device_path) numsensors_input_path_mapping[x] = NUMSENSORS_PATH.format( hwmon_input_node_mapping[x], hwmon_dir) numsensors_path = numsensors_input_path_mapping[x] time.sleep(1) - cmd = ("sudo echo 0 > %s" %numsensors_path) - os.system(cmd) + cmd = "0" + write_file(cmd, numsensors_path) return True diff --git a/platform/broadcom/sonic-platform-modules-juniper/qfx5200/utils/show_thresholds b/platform/broadcom/sonic-platform-modules-juniper/qfx5200/utils/show_thresholds index 29d584e7f3..9dd58b52ae 100755 --- a/platform/broadcom/sonic-platform-modules-juniper/qfx5200/utils/show_thresholds +++ b/platform/broadcom/sonic-platform-modules-juniper/qfx5200/utils/show_thresholds @@ -1,6 +1,6 @@ #!/usr/bin/env python import os -import commands +from sonic_py_common.general import getstatusoutput_noshell def fantype_detect(): @@ -15,9 +15,8 @@ def fantype_detect(): for filename in os.listdir(refpgaTMC_path): if filename.endswith('_type'): fantype_path = os.path.join(refpgaTMC_path, filename) - cat_string = "cat " - fantype_string = cat_string + fantype_path - status,fan_type=commands.getstatusoutput(fantype_string) + fantype_string = ["cat", fantype_path] + status, fan_type = getstatusoutput_noshell(fantype_string) if ((fan_type == AFO) or (fan_type == AFI)): return fan_type else: diff --git a/platform/broadcom/sonic-platform-modules-juniper/qfx5210/utils/juniper_qfx5210_monitor.py b/platform/broadcom/sonic-platform-modules-juniper/qfx5210/utils/juniper_qfx5210_monitor.py index 77eac52342..79b3284f13 100755 --- a/platform/broadcom/sonic-platform-modules-juniper/qfx5210/utils/juniper_qfx5210_monitor.py +++ b/platform/broadcom/sonic-platform-modules-juniper/qfx5210/utils/juniper_qfx5210_monitor.py @@ -34,13 +34,13 @@ try: import os - import commands import subprocess import logging import logging.config import logging.handlers import time import glob + from sonic_py_common.general import getstatusoutput_noshell except ImportError as e: raise ImportError('%s - required module not found' % str(e)) @@ -305,10 +305,12 @@ class QFX5210_ThermalUtil(object): firethr = FireThresholdSecsRemaining - 20 if firethr == 0: logging.critical('CRITICAL: Fire Threshold reached: System is going to shutdown now') - os.system("echo 'CRITICAL: Fire Threshold reached: System is going to shutdown now' > /dev/console") + with open("/dev/console", 'w') as f: + f.write('CRITICAL: Fire Threshold reached: System is going to shutdown now\n') else: logging.critical('CRITICAL: Fire Threshold reached: System is going to shutdown in %s seconds', firethr) - os.system("echo 'CRITICAL: Fire Threshold reached: System is going to shutdown in %s seconds' > /dev/console" % firethr) + with open("/dev/console", 'w') as f: + f.write('CRITICAL: Fire Threshold reached: System is going to shutdown in %s seconds\n' % firethr) FireThresholdSecsRemaining = FireThresholdSecsRemaining - 20 logging.critical('CRITICAL: Value of FireThresholdSecsRemaining %s seconds', FireThresholdSecsRemaining) @@ -316,8 +318,8 @@ class QFX5210_ThermalUtil(object): if (FireThresholdSecsRemaining == 0): isFireThresholdReached == False time.sleep(20) - cmd = "poweroff" - os.system(cmd) + cmd = ["poweroff"] + subprocess.call(cmd) for x in range(self.SENSOR_CORETEMP_NUM_ON_MAIN_BOARD): if x < self.SENSOR_NUM_ON_MAIN_BOARD: @@ -330,8 +332,8 @@ class QFX5210_ThermalUtil(object): logging.debug('Reading ASIC Temp value using bcmcmd') proc = subprocess.Popen("bcmcmd \"show temp\" | grep \"maximum peak temperature\" | awk '{ print $5 }' > /var/log/asic_value 2>&1 & ",shell=True) time.sleep(2) - cmd = "kill -9 %s"%(proc.pid) - commands.getstatusoutput(cmd) + cmd = ["kill", "-9", proc.pid] + getstatusoutput_noshell(cmd) if os.stat("/var/log/asic_value").st_size == 0: value = PrevASICValue @@ -346,7 +348,7 @@ class QFX5210_ThermalUtil(object): logging.debug('Reading from ASIC Temp file: %s', value) logging.debug('Reading from Prev ASIC Temp Value: %s', PrevASICValue) - os.system('rm /var/log/asic_value') + subprocess.call(['rm', '/var/log/asic_value']) # 60% Duty Cycle for AFO and 70% Duty Cycle for AFI if value > temp_policy[x][0][1] and value <= temp_policy[x][0][2]: @@ -389,7 +391,9 @@ class QFX5210_ThermalUtil(object): isFireThresholdReached = True if (isFireThresholdPrint == True): logging.critical('CRITICAL: Fire Threshold reached: System is going to shutdown in 120 seconds') - os.system("echo 'CRITICAL: Fire Threshold reached: System is going to shutdown in 120 seconds' > /dev/console") + with open("/dev/console", 'w') as f: + f.write('CRITICAL: Fire Threshold reached: System is going to shutdown in 120 seconds') + isFireThresholdPrint = False logging.debug('Temp Sensor is set to FIRE SHUTDOWN Flag') @@ -403,7 +407,8 @@ class QFX5210_ThermalUtil(object): logging.debug('Temp Sensor is set to Red Alarm Flag') if (isFireThresholdReached == True): logging.critical('CRITICAL: System Stabilized, not shutting down') - os.system("echo 'CRITICAL: System Stabilized, not shutting down' > /dev/console") + with open("/dev/console", 'w') as f: + f.write('CRITICAL: System Stabilized, not shutting down\n') FireThresholdSecsRemaining = 120 isFireThresholdReached = False @@ -414,7 +419,8 @@ class QFX5210_ThermalUtil(object): logging.debug('Temp Sensor is set to Yellow Alarm Flag') if (isFireThresholdReached == True): logging.critical('CRITICAL: System Stabilized, not shutting down') - os.system("echo 'CRITICAL: System Stabilized, not shutting down' > /dev/console") + with open("/dev/console", 'w') as f: + f.write('CRITICAL: System Stabilized, not shutting down\n') FireThresholdSecsRemaining = 120 isFireThresholdReached = False @@ -442,7 +448,8 @@ class QFX5210_ThermalUtil(object): if (isFireThresholdReached == True): logging.critical('CRITICAL: System Stabilized, not shutting down') - os.system("echo 'CRITICAL: System Stabilized, not shutting down' > /dev/console") + with open("/dev/console", 'w') as f: + f.write('CRITICAL: System Stabilized, not shutting down') FireThresholdSecsRemaining = 120 isFireThresholdReached = False logging.debug('Temp Sensor is set to 80% Prev Duty Cycle Flag') @@ -457,7 +464,8 @@ class QFX5210_ThermalUtil(object): if (isFireThresholdReached == True): logging.critical('CRITICAL: System Stabilized, not shutting down') - os.system("echo 'CRITICAL: System Stabilized, not shutting down' > /dev/console") + with open("/dev/console", 'w') as f: + f.write('CRITICAL: System Stabilized, not shutting down\n') FireThresholdSecsRemaining = 120 isFireThresholdReached = False @@ -483,7 +491,8 @@ class QFX5210_ThermalUtil(object): if (isFireThresholdReached == True): logging.critical('CRITICAL: System Stabilized, not shutting down') - os.system("echo 'CRITICAL: System Stabilized, not shutting down' > /dev/console") + with open("/dev/console", 'w') as f: + f.write('CRITICAL: System Stabilized, not shutting down\n') FireThresholdSecsRemaining = 120 isFireThresholdReached = False @@ -504,7 +513,8 @@ class QFX5210_ThermalUtil(object): if (isFireThresholdReached == True): logging.critical('CRITICAL: System Stabilized, not shutting down') - os.system("echo 'CRITICAL: System Stabilized, not shutting down' > /dev/console") + with open("/dev/console", 'w') as f: + f.write('CRITICAL: System Stabilized, not shutting down\n') FireThresholdSecsRemaining = 120 isFireThresholdReached = False logging.debug('Temp Sensor is set to 60% Duty Cycle Flag') diff --git a/platform/broadcom/sonic-platform-modules-juniper/qfx5210/utils/juniper_qfx5210_util.py b/platform/broadcom/sonic-platform-modules-juniper/qfx5210/utils/juniper_qfx5210_util.py index 5479c0e041..21e4c71cce 100755 --- a/platform/broadcom/sonic-platform-modules-juniper/qfx5210/utils/juniper_qfx5210_util.py +++ b/platform/broadcom/sonic-platform-modules-juniper/qfx5210/utils/juniper_qfx5210_util.py @@ -34,13 +34,12 @@ command: set : change board setting with fan|led|sfp """ -import os import commands import sys, getopt import binascii import logging import time - +import subprocess @@ -55,8 +54,8 @@ FORCE = 0 FUNCTION_NAME = '/var/log/juniper_qfx5210_util' if DEBUG == True: - print sys.argv[0] - print 'ARGV :', sys.argv[1:] + print(sys.argv[0]) + print('ARGV :', sys.argv[1:]) def main(): @@ -81,10 +80,10 @@ def main(): format= '[%(asctime)s] {%(pathname)s:%(lineno)d} %(levelname)s - %(message)s', datefmt='%H:%M:%S') - if DEBUG == True: - print options - print args - print len(sys.argv) + if DEBUG is True: + print(options) + print(args) + print(len(sys.argv)) # set up logging to console if log_level == logging.DEBUG: console = logging.StreamHandler() @@ -127,45 +126,45 @@ def main(): else: show_help() - DisableWatchDogCmd = '/usr/sbin/i2cset -f -y 0 0x65 0x3 0x04' + DisableWatchDogCmd = ['/usr/sbin/i2cset', '-f', '-y', '0', '0x65', '0x3', '0x04'] # Disable watchdog try: - os.system(DisableWatchDogCmd) + subprocess.call(DisableWatchDogCmd) except OSError: - print 'Error: Execution of "%s" failed', DisableWatchDogCmd + print('Error: Execution of "%s" failed', DisableWatchDogCmd) return False time.sleep(1) # Invoking the script which retrieves the data from Board EEPROM and storing in file - EEPROMDataCmd = 'python /usr/share/sonic/device/x86_64-juniper_qfx5210-r0/plugins/qfx5210_eeprom_data.py' + EEPROMDataCmd = ['python', '/usr/share/sonic/device/x86_64-juniper_qfx5210-r0/plugins/qfx5210_eeprom_data.py'] try: - os.system(EEPROMDataCmd) + subprocess.call(EEPROMDataCmd) except OSError: - print 'Error: Execution of "%s" failed', EEPROMDataCmd + print('Error: Execution of "%s" failed', EEPROMDataCmd) return False return True def show_help(): - print __doc__ % {'scriptName' : sys.argv[0].split("/")[-1]} + print(__doc__ % {'scriptName' : sys.argv[0].split("/")[-1]}) sys.exit(0) def show_set_help(): cmd = sys.argv[0].split("/")[-1]+ " " + args[0] - print cmd +" [led|sfp|fan]" - print " use \""+ cmd + " led 0-4 \" to set led color" - print " use \""+ cmd + " fan 0-100\" to set fan duty percetage" - print " use \""+ cmd + " sfp 1-32 {0|1}\" to set sfp# tx_disable" + print(cmd +" [led|sfp|fan]") + print(" use \""+ cmd + " led 0-4 \" to set led color") + print(" use \""+ cmd + " fan 0-100\" to set fan duty percetage") + print(" use \""+ cmd + " sfp 1-32 {0|1}\" to set sfp# tx_disable") sys.exit(0) def show_eeprom_help(): cmd = sys.argv[0].split("/")[-1]+ " " + args[0] - print " use \""+ cmd + " 1-32 \" to dump sfp# eeprom" + print(" use \""+ cmd + " 1-32 \" to dump sfp# eeprom") sys.exit(0) def my_log(txt): - if DEBUG == True: - print txt + if DEBUG is True: + print(txt) return def log_os_system(cmd, show): @@ -283,7 +282,7 @@ def device_install(): status, output = log_os_system(mknod[i], 1) if status: - print output + print(output) if FORCE == 0: return status @@ -291,12 +290,12 @@ def device_install(): path = "/sys/bus/i2c/devices/i2c-"+str(sfp_map[i])+"/new_device" status, output =log_os_system("echo optoe1 0x50 > " + path, 1) if status: - print output + print(output) if FORCE == 0: return status status, output =log_os_system("echo Port"+str(i)+" > /sys/bus/i2c/devices/"+str(sfp_map[i])+"-0050/port_name", 1) if status: - print output + print(output) if FORCE == 0: return status return @@ -310,7 +309,7 @@ def device_uninstall(): target = "/sys/bus/i2c/devices/i2c-"+str(sfp_map[i])+"/delete_device" status, output =log_os_system("echo 0x50 > "+ target, 1) if status: - print output + print(output) if FORCE == 0: return status @@ -323,7 +322,7 @@ def device_uninstall(): temp[-1] = temp[-1].replace('new_device', 'delete_device') status, output = log_os_system(" ".join(temp), 1) if status: - print output + print(output) if FORCE == 0: return status @@ -351,14 +350,14 @@ def do_install(): if FORCE == 0: return status else: - print PROJECT_NAME.upper()+" devices detected...." + print(PROJECT_NAME.upper()+" devices detected....") return def do_uninstall(): logging.info('Checking system....') if not device_exist(): - print PROJECT_NAME.upper() +" has no device installed...." + print(PROJECT_NAME.upper() +" has no device installed....") else: logging.info('Removing device....') status = device_uninstall() @@ -367,7 +366,7 @@ def do_uninstall(): return status if driver_check()== False : - print PROJECT_NAME.upper() +" has no driver installed...." + print(PROJECT_NAME.upper() +" has no driver installed....") else: logging.info('Removing installed driver....') status = driver_uninstall() @@ -421,7 +420,7 @@ def devices_info(): ALL_DEVICE[key][ key+str(i+1)].append(path) #show dict all in the order - if DEBUG == True: + if DEBUG is True: for i in sorted(ALL_DEVICE.keys()): print(i+": ") for j in sorted(ALL_DEVICE[i].keys()): @@ -448,22 +447,22 @@ def show_eeprom(index): else: log = 'Failed : no hexdump cmd!!' logging.info(log) - print log + print(log) return 1 - print node + ":" + print(node + ":") ret, log = log_os_system(hex_cmd +" -C "+node, 1) if ret==0: - print log + print(log) else: - print "**********device no found**********" + print("**********device no found**********") return def set_device(args): global DEVICE_NO global ALL_DEVICE if system_ready()==False: - print("System's not ready.") + print("System's not ready.") print("Please install first!") return @@ -474,7 +473,7 @@ def set_device(args): if int(args[1])>4: show_set_help() return - #print ALL_DEVICE['led'] + #print ALL_DEVICE['led'] for i in range(0,len(ALL_DEVICE['led'])): for k in (ALL_DEVICE['led']['led'+str(i+1)]): ret, log = log_os_system("echo "+args[1]+" >"+k, 1) @@ -489,10 +488,10 @@ def set_device(args): node = node.replace(node.split("/")[-1], 'fan_duty_cycle_percentage') ret, log = log_os_system("cat "+ node, 1) if ret==0: - print ("Previous fan duty: " + log.strip() +"%") + print("Previous fan duty: " + log.strip() +"%") ret, log = log_os_system("echo "+args[1]+" >"+node, 1) if ret==0: - print ("Current fan duty: " + args[1] +"%") + print("Current fan duty: " + args[1] +"%") return ret elif args[0]=='sfp': if int(args[1])> DEVICE_NO[args[0]] or int(args[1])==0: @@ -506,7 +505,7 @@ def set_device(args): show_set_help() return - #print ALL_DEVICE[args[0]] + #print ALL_DEVICE[args[0]] for i in range(0,len(ALL_DEVICE[args[0]])): for j in ALL_DEVICE[args[0]][args[0]+str(args[1])]: if j.find('tx_disable')!= -1: @@ -531,26 +530,24 @@ def device_traversal(): if len(ALL_DEVICE)==0: devices_info() for i in sorted(ALL_DEVICE.keys()): - print("============================================") + print("============================================") print(i.upper()+": ") print("============================================") for j in sorted(ALL_DEVICE[i].keys(), key=get_value): - print " "+j+":", + print(" "+j+":", end=' ') for k in (ALL_DEVICE[i][j]): ret, log = log_os_system("cat "+k, 0) func = k.split("/")[-1].strip() func = re.sub(j+'_','',func,1) func = re.sub(i.lower()+'_','',func,1) if ret==0: - print func+"="+log+" ", + print(func+"="+log+" ") else: - print func+"="+"X"+" ", - print + print(func+"="+"X"+" ") print("----------------------------------------------------------------") - print return def device_exist(): diff --git a/platform/broadcom/sonic-platform-modules-juniper/sonic_platform/chassis.py b/platform/broadcom/sonic-platform-modules-juniper/sonic_platform/chassis.py index 9eb9b07a61..51b846b77e 100755 --- a/platform/broadcom/sonic-platform-modules-juniper/sonic_platform/chassis.py +++ b/platform/broadcom/sonic-platform-modules-juniper/sonic_platform/chassis.py @@ -36,11 +36,11 @@ try: import os - import subprocess import sys import time import syslog from sonic_platform_base.chassis_base import ChassisBase + from sonic_py_common.general import getstatusoutput_noshell except ImportError as e: raise ImportError(str(e) + "- required module not found") @@ -242,7 +242,7 @@ class Chassis(ChassisBase): log_info("Juniper Platform name: {} and {}".format(self.get_platform_name(), platform_name)) if str(platform_name) == "x86_64-juniper_networks_qfx5210-r0": log_info("Juniper Platform QFX5210 ") - status, last_reboot_reason = subprocess.getstatusoutput("i2cget -f -y 0 0x65 0x24") + status, last_reboot_reason = getstatusoutput_noshell(["i2cget", "-f", "-y", "0", "0x65", "0x24"]) if (status == 0): if last_reboot_reason == "0x80": return (ChassisBase.REBOOT_CAUSE_NON_HARDWARE, None) @@ -256,7 +256,7 @@ class Chassis(ChassisBase): return (ChassisBase.REBOOT_CAUSE_HARDWARE_OTHER, "Unknown reason") else: time.sleep(3) - status, last_reboot_reason = subprocess.getstatusoutput("i2cget -f -y 0 0x65 0x24") + status, last_reboot_reason = getstatusoutput_noshell(["i2cget", "-f", "-y", "0", "0x65", "0x24"]) if last_reboot_reason == "0x80": return (ChassisBase.REBOOT_CAUSE_NON_HARDWARE, None) elif last_reboot_reason == "0x40" or last_reboot_reason == "0x08": @@ -270,9 +270,9 @@ class Chassis(ChassisBase): elif str(platform_name) == "x86_64-juniper_networks_qfx5200-r0" : log_info("Juniper Platform QFX5200 ") - status, major_version = subprocess.getstatusoutput("busybox devmem 0xFED50000 8") - status, minor_version = subprocess.getstatusoutput("busybox devmem 0xFED50001 8") - status, last_reboot_reason = subprocess.getstatusoutput("busybox devmem 0xFED50004 8") + status, major_version = getstatusoutput_noshell(["busybox", "devmem", "0xFED50000", "8"]) + status, minor_version = getstatusoutput_noshell(["busybox", "devmem", "0xFED50001", "8"]) + status, last_reboot_reason = getstatusoutput_noshell(["busybox", "devmem", "0xFED50004", "8"]) if (status == 0): if (major_version == "0x31") and (minor_version == "0x03") and (last_reboot_reason == "0x80"): return (ChassisBase.REBOOT_CAUSE_NON_HARDWARE, None) @@ -288,9 +288,9 @@ class Chassis(ChassisBase): return (ChassisBase.REBOOT_CAUSE_HARDWARE_OTHER, "Unknown reason") else: time.sleep(3) - status, major_version = subprocess.getstatusoutput("busybox devmem 0xFED50000 8") - status, minor_version = subprocess.getstatusoutput("busybox devmem 0xFED50001 8") - status, last_reboot_reason = subprocess.getstatusoutput("busybox devmem 0xFED50004 8") + status, major_version = getstatusoutput_noshell(["busybox", "devmem", "0xFED50000", "8"]) + status, minor_version = getstatusoutput_noshell(["busybox", "devmem", "0xFED50001", "8"]) + status, last_reboot_reason = getstatusoutput_noshell(["busybox", "devmem", "0xFED50004", "8"]) if (status == 0): if (major_version == "0x31") and (minor_version == "0x03") and (last_reboot_reason == "0x80"): return (ChassisBase.REBOOT_CAUSE_NON_HARDWARE, None)