How to use rpm_verify method in avocado

Best Python code snippet using avocado_python

system.py

Source:system.py Github

copy

Full Screen

1#!/usr/bin/env python2# coding: utf-83# Copyright (c) 2020 Huawei Technologies Co., Ltd.4# oec-hardware is licensed under the Mulan PSL v2.5# You can use this software according to the terms and conditions of the Mulan PSL v2.6# You may obtain a copy of Mulan PSL v2 at:7# http://license.coscl.org.cn/MulanPSL28# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR9# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR10# PURPOSE.11# See the Mulan PSL v2 for more details.12# Create: 2020-04-0113"""System Test"""14import os15import sys16import re17import argparse18sys.path.append('/usr/share/oech/lib/')19from hwcompatible.test import Test20from hwcompatible.command import Command21from hwcompatible.sysinfo import SysInfo22from hwcompatible.env import CertEnv23from hwcompatible.document import Document24class SystemTest(Test):25 """26 System Test27 """28 def __init__(self):29 Test.__init__(self)30 self.pri = 131 self.sysinfo = SysInfo(CertEnv.releasefile)32 self.args = None33 self.logpath = ""34 def setup(self, args=None):35 """36 Initialization before test37 :param args:38 :return:39 """40 self.args = args or argparse.Namespace()41 #self.logpath = os.path.dirname(os.path.realpath(__file__)) + "/system.log"42 self.logpath = getattr(args, "logdir", None) + "/system.log"43 def test(self):44 """45 test case46 :return:47 """48 os.system("uname -a &>> %s" % self.logpath)49 print("")50 os.system("lsmod &>> %s" % self.logpath)51 print("")52 os.system("dmidecode &>> %s" % self.logpath)53 sys.stdout.flush()54 return_code = True55 if not self.check_certrpm():56 return_code = False57 if not self.check_kernel():58 return_code = False59 if not self.check_selinux():60 return_code = False61 return return_code62 def check_certrpm(self):63 """64 Check installed cert package65 :return:66 """67 print("\nChecking installed cert package...")68 return_code = True69 for cert_package in ["oec-hardware"]:70 rpm_verify = Command(71 "rpm -V --nomtime --nomode --nocontexts %s &>> %s" % (cert_package, self.logpath))72 try:73 rpm_verify.echo()74 sys.stdout.flush()75 if rpm_verify.output and len(rpm_verify.output) > 0:76 return_code = False77 except Exception:78 print("Error: files in %s have been tampered." % cert_package)79 return_code = False80 return return_code81 def check_kernel(self):82 """83 Check kernel84 :return:85 """86 print("\nChecking kernel...")87 kernel_rpm = self.sysinfo.kernel_rpm88 os_version = self.sysinfo.product + " " + self.sysinfo.get_version()89 print("Kernel RPM: %s" % kernel_rpm)90 print("OS Version: %s" % os_version)91 print("")92 return_code = True93 if self.sysinfo.debug_kernel:94 print("Error: debug kernel.")95 return_code = False96 kernel_dict = Document(CertEnv.kernelinfo)97 if not kernel_dict.load():98 print("Error: get kernel info fail.")99 return False100 try:101 if kernel_dict.document[os_version] != self.sysinfo.kernel_version:102 print("Error: kernel %s check GA status fail." %103 self.sysinfo.kernel_version)104 return_code = False105 except Exception as error:106 print("Error: %s is not supported." % os_version)107 return_code = False108 try:109 tainted_file = open("/proc/sys/kernel/tainted", "r")110 tainted = int(tainted_file.readline())111 if tainted != 0:112 print("Warning: kernel is tainted (value = %u)." % tainted)113 if tainted & 1:114 print("Error: module with a non-GPL license has been loaded.")115 return_code = False116 modules = self.get_modules("P")117 print("Non-GPL modules:")118 for module in modules:119 print(module)120 print("")121 if tainted & (1 << 12):122 modules = self.get_modules("O")123 print("Out-of-tree modules:")124 for module in modules:125 print(module)126 # self.abi_check(module)127 return_code = False128 print("")129 if tainted & (1 << 13):130 modules = self.get_modules("E")131 print("Unsigned modules:")132 for module in modules:133 print(module)134 print("")135 tainted_file.close()136 except Exception as concrete_error:137 print("Error: could not determine if kernel is tainted. \n",138 concrete_error)139 return_code = False140 except_list = ["/modules.dep$", "/modules.symbols$", "/modules.dep.bin$",141 "/modules.symbols.bin$"]142 if os.system("rpm -V --nomtime --nomode --nocontexts %s | grep -Ev '%s'" %143 (kernel_rpm, "|".join(except_list))) == 0:144 print("Error: files from %s were modified.\n" % kernel_rpm)145 return_code = False146 try:147 params = Command("cat /proc/cmdline").get_str()148 print("Boot Parameters: %s" % params)149 except Exception as concrete_error:150 print("Error: could not determine boot parameters. \n", concrete_error)151 return_code = False152 return return_code153 def get_modules(self, sign):154 """155 Get the module with signs character156 :param sign:157 :return:158 """159 pattern = re.compile(r"^(?P<mod_name>\w+)[\s\S]+\((?P<signs>[A-Z]+)\)")160 proc_modules = open("/proc/modules")161 modules = list()162 for line in proc_modules.readlines():163 match = pattern.match(line)164 if match:165 if sign in match.group("signs"):166 modules.append(match.group("mod_name"))167 proc_modules.close()168 return modules169 def abi_check(self, module):170 """171 Check abi whitelist172 :param module:173 :return:174 """175 whitelist_path = [("/lib/modules/kabi-current/kabi_whitelist_" + self.sysinfo.arch),176 ("/lib/modules/kabi/kabi_whitelist_" + self.sysinfo.arch),177 ("/usr/src/kernels/%s/kabi_whitelist" %178 self.sysinfo.kernel)179 ]180 whitelist = ""181 for whitelist in whitelist_path:182 if os.path.exists(whitelist):183 break184 if not os.path.exists(whitelist):185 print(186 "Error: could not find whitelist file in any of the following locations:")187 print("\n".join(whitelist_path))188 return False189 whitelist_symbols = self.read_abi_whitelist(whitelist)190 if not whitelist_symbols:191 return False192 module_symbols = self.read_module(module)193 if not module_symbols:194 return False195 extra_symbols = list()196 for symbol in module_symbols:197 if symbol not in whitelist_symbols:198 extra_symbols.append(symbol)199 black_symbols = list()200 if extra_symbols:201 greylist = "/usr/share/doc/kmod-%s/greylist.txt" % module202 if os.path.exists(greylist):203 print("checking greylist for %s" % module)204 greylist_symbols = self.read_abi_whitelist(greylist)205 for symbol in extra_symbols:206 if symbol not in greylist_symbols:207 black_symbols.append(symbol)208 else:209 black_symbols = extra_symbols210 if black_symbols:211 print("Error: The following symbols are used by %s are not on the ABI \212 whitelist." % module)213 for symbol in black_symbols:214 print(symbol)215 return False216 print("")217 return True218 def read_abi_whitelist(self, whitelist):219 """220 Read abi whitelist221 :param whitelist:222 :return:223 """224 symbols = list()225 if not os.path.isfile(whitelist):226 print("Error: Cannot read whitelist file")227 return None228 whitelistfile = open(whitelist, "r")229 while True:230 line = whitelistfile.readline()231 if line == "":232 break233 if line == "\n":234 continue235 line.split()236 if line[0] == '[':237 # group = line[1:-2]238 continue239 symbol = line.strip()240 symbols.append(symbol)241 return symbols242 def read_module(self, module):243 """244 Read module245 :param module:246 :return:247 """248 symbols = list()249 module_file = self.get_modulefile(module)250 if not module_file:251 print("Error: Can not find module file for %s" % module)252 return None253 if not os.path.isfile(module_file):254 print("Error: Cannot read module file %s" % module_file)255 return None256 if module_file[-2:] == "ko":257 n_m = os.popen('modprobe --dump-modversions ' + module_file)258 else:259 n_m = open(module_file, "r")260 while True:261 line = n_m.readline()262 if line == "":263 break264 symbols.append(line)265 n_m.close()266 return self.readSymbols(symbols)267 def get_modulefile(self, module):268 """269 Get module file270 :param module:271 :return:272 """273 try:274 modulefile = Command("modinfo -F filename %s" % module).get_str()275 if os.path.islink(modulefile):276 modulefile = os.readlink(modulefile)277 return modulefile278 except Exception:279 print("Error: could no find module file for %s:" % module)280 return None281 def check_selinux(self):282 """283 check selinux284 :return:285 """286 print("\nChecking selinux...")287 status = os.system(288 "/usr/sbin/sestatus | grep 'SELinux status' | grep -qw 'enabled'")289 mode = os.system(290 "/usr/sbin/sestatus | grep 'Current mode' | grep -qw 'enforcing'")291 if mode == 0 and status == 0:292 print("SElinux is enforcing as expect.")293 return True294 else:295 print('status: ' + str(status))296 print('mode: ' + str(mode))297 print("SElinux is not enforcing, expect is enforcing.")298 os.system("/usr/sbin/sestatus")299 return False300if __name__ == "__main__":301 main = SystemTest()302 main.setup()...

Full Screen

Full Screen

rpm.py

Source:rpm.py Github

copy

Full Screen

...108 return True109 except process.CmdError as details:110 log.error(details)111 return False112 def rpm_verify(self, package_name):113 """114 Verify an RPM package with an installed one.115 :param str package_name: name of the verified package116 :returns: whether the verification was successful117 :rtype: bool118 """119 logging.info("Verifying package information.")120 cmd = "rpm -V " + package_name121 result = process.run(cmd, ignore_status=True)122 # unstable approach but currently works123 # installed_pattern = r"\s" + package_name + r" is installed\s+"124 # match = re.search(installed_pattern, result)125 match = (result.exit_status == 0)126 if match:127 logging.info("Verification successful.")128 return True129 else:130 logging.info(result.stdout_text.rstrip())131 return False132 def rpm_erase(self, package_name):133 """134 Erase an RPM package.135 :param str package_name: name of the erased package136 :returns: whether file is erased properly137 :rtype: bool138 """139 logging.warning("Erasing rpm package %s", package_name)140 cmd = "rpm -e " + package_name141 result = process.run(cmd, ignore_status=True)142 if result.exit_status:143 return False144 return True145 def prepare_source(self, spec_file, dest_path=None):146 """147 Rpmbuild the spec path and return build dir148 :param spec_path: spec path to install149 :return path: build directory150 """151 build_option = "-bp"152 if dest_path is not None:153 build_option += " --define '_builddir %s'" % dest_path154 else:155 log.error("Please provide a valid path")156 return ""157 try:158 process.system("rpmbuild %s %s" % (build_option, spec_file))159 return os.path.join(dest_path, os.listdir(dest_path)[0])160 except process.CmdError as details:161 log.error(details)162 return ""163 def find_rpm_packages(self, rpm_dir):164 """165 Extract product dependencies from a defined RPM directory and all its subdirectories.166 :param str rpm_dir: directory to search in167 :returns: found RPM packages168 :rtype: [str]169 """170 subpaths = os.listdir(rpm_dir)171 subpacks = []172 for subpath in subpaths:173 if subpath == "." or subpath == "..":174 continue175 new_filepath = rpm_dir + "/" + subpath176 logging.debug("Checking path for rpm %s", new_filepath)177 # if path is file validate name and inject178 if os.path.isfile(new_filepath) and re.search(r"\s*.rpm$", os.path.basename(new_filepath)):179 logging.info("Marking package %s for setup", new_filepath)180 subpacks.append(new_filepath)181 elif os.path.isdir(new_filepath):182 subpacks += self.find_rpm_packages(new_filepath)183 return subpacks184 def perform_setup(self, packages, no_dependencies=False):185 """186 General RPM setup with automatic handling of dependencies based on187 install attempts.188 :param packages: the RPM packages to install in dependency-friendly order189 :type packages: [str]190 :returns: whether setup completed successfully191 :rtype: bool192 """193 while len(packages) > 0:194 logging.debug("Trying to install: %s", packages)195 failed_packages = []196 for package_path in packages:197 package_file = os.path.basename(package_path)198 package_name = "-".join(package_file.split('-')[0:-2])199 logging.debug("%s -> %s", package_file, package_name)200 installed = self.check_installed(package_name)201 verified = self.rpm_verify(package_name) if installed else False202 if installed and not verified:203 self.rpm_erase(package_name)204 if not installed or not verified:205 success = self.rpm_install(package_path, no_dependencies)206 if not success:207 failed_packages.append(package_path)208 if len(packages) == len(failed_packages) > 0:209 logging.warning("Some of the rpm packages could not be "210 "installed: %s", ", ".join(failed_packages))211 return False212 packages = failed_packages...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run avocado automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful