How to use install_pkg method in autotest

Best Python code snippet using autotest_python

show_install.py

Source:show_install.py Github

copy

Full Screen

1"""show_install.py2 supported commands:3 * show install summary4 * show install rollback5 * show install rollbackId6 * show install state7 * show install package SMU/subpkg8 * show install version all9 * show install version summary10 * show install version value {value}11 * show exception12"""13# Python14import re15import random16# Metaparser17from genie.metaparser import MetaParser18from genie.metaparser.util.schemaengine import (Schema,19 Any,20 Optional)21# import parser utils22from genie.libs.parser.utils.common import Common23class ShowInstallSummarySchema(MetaParser):24 """Schema for show install summary"""25 schema = {26 'location': {27 Any(): {28 'pkg_state': {29 Any(): {30 'type': str,31 'state': str,32 'filename_version': str,33 }34 },35 'auto_abort_timer': str,36 Optional('time_before_rollback'): str,37 },38 },39 }40class ShowInstallSummary(ShowInstallSummarySchema):41 """Parser for show install summary"""42 cli_command = 'show install summary'43 def cli(self, output=None):44 if output is None:45 # get output from device46 output = self.device.execute(self.cli_command)47 # initial return dictionary48 ret_dict = {}49 index = 050 # initial regexp pattern51 # [ R0 ] Installed Package(s) Information:52 p1 = re.compile(r'^\[ +(?P<location>[\S ]+)\] +Installed Package'53 r'\(s\) +Information:$')54 # SMU U bootflash:utah.bm.smu.may15.bin55 # IMG C 10.69.1.0.6698256 p2 = re.compile(r'^(?P<type>\S+) + (?P<state>\w) +(?P<filename_version>\S+)$')57 58 # Auto abort timer: active on install_activate, time before rollback - 01:49:4259 p3 = re.compile(r'^Auto +abort +timer: +(?P<auto_abort_timer>[\S ]+), +'60 r'time +before +rollback +\- +(?P<time_before_rollback>\S+)$')61 # Auto abort timer: active on install_activate62 p4 = re.compile(r'^Auto +abort +timer: +(?P<auto_abort_timer>[\S ]+)$')63 for line in output.splitlines():64 line = line.strip()65 66 # [ R0 ] Installed Package(s) Information:67 m = p1.match(line)68 if m:69 group = m.groupdict()70 location = group['location'].strip()71 location_dict = ret_dict.setdefault('location', {}). \72 setdefault(location, {})73 continue74 # SMU U bootflash:utah.bm.smu.may15.bin75 # IMG C 10.69.1.0.6698276 m = p2.match(line)77 if m:78 group = m.groupdict()79 index += 180 install_dict = location_dict.setdefault('pkg_state', {}). \81 setdefault(index, {})82 install_dict.update({'type': group['type']})83 install_dict.update({'state': group['state']})84 install_dict.update({'filename_version': group['filename_version']})85 continue86 87 # Auto abort timer: active on install_activate, time before rollback - 01:49:4288 m = p3.match(line)89 if m:90 group = m.groupdict()91 location_dict.update({'auto_abort_timer': group['auto_abort_timer']})92 time_before_rollback = group.get('time_before_rollback', None)93 if time_before_rollback:94 location_dict.update({'time_before_rollback': time_before_rollback})95 continue96 97 # Auto abort timer: active on install_activate98 m = p4.match(line)99 if m:100 group = m.groupdict()101 location_dict.update({'auto_abort_timer': group['auto_abort_timer']})102 continue103 return ret_dict104class ShowInstallRollbackSchema(MetaParser):105 """Schema for show install rollback"""106 schema = {107 'install_rollback': {108 Any(): {109 'id': int,110 'label': str,111 'description': str,112 },113 },114 }115class ShowInstallRollback(ShowInstallRollbackSchema):116 """Parser for show install rollback"""117 cli_command = 'show install rollback'118 def cli(self, output=None):119 if output is None:120 output = self.device.execute(self.cli_command)121 # initial return dictionary122 ret_dict = {}123 index = 0124 # 5 No_Label No Description125 p1 = re.compile(r'^(?P<id>\d+)\s*(?P<label>(\S+ ){1,})\s{2,}(?P<description>.*)$')126 for line in output.splitlines():127 line = line.strip()128 m = p1.match(line)129 if m:130 index += 1131 group = m.groupdict()132 rollback_dict = ret_dict.setdefault('install_rollback', {}).setdefault(index, {})133 rollback_dict.update({'id': int(group['id'])})134 rollback_dict.update({'label': group['label'].strip()})135 rollback_dict.update({'description': group['description']})136 continue137 return ret_dict138class ShowInstallRollbackIdSchema(MetaParser):139 """Schema for show install rollback id <id>"""140 schema = {141 'id': {142 Any(): {143 'label': str,144 'description': str,145 'date': str,146 'time': str,147 'reload_required': str,148 Optional('type'): {149 Any(): {150 'state': str,151 'filename_version': str152 }153 }154 },155 },156 }157class ShowInstallRollbackId(ShowInstallRollbackIdSchema):158 """Parser for show install rollback id"""159 cli_command = 'show install rollback id {rollback_id}'160 def cli(self, rollback_id='', output=None):161 if output is None:162 # get output from device163 output = self.device.execute(self.cli_command.format(rollback_id=rollback_id))164 # initial return dictionary165 ret_dict = {}166 # Rollback id - 5 (Created on 2021-10-21 16:34:06.000000000 +0000)167 p1 = re.compile(r'Rollback\s*id\s*-\s*(?P<rollback_id>\d+)\s*\('168 r'Created\s*on\s*(?P<date>\d*-\d*-\d*)\s*'169 r'(?P<time>\d*:\d*:\d*.\d*)')170 # Label: No Label171 p2 = re.compile(r'Label:\s*(?P<label>.*)')172 # Description: No Description173 p3 = re.compile(r'Description:\s*(?P<description>.*)')174 # Reload required: NO175 p4 = re.compile(r'Reload\s*required:\s*(?P<reload_required>.*)')176 # IMG C 17.08.01.0.148528 |177 # SMU C /flash1/user/cat9k_iosxe.2021-10-06_22.52_shidogra.53.CSCxx12353.SSA.smu.bin178 p5 = re.compile(r'^(?P<type>\S+) + (?P<state>\w) +(?P<filename_version>\S+)$')179 for line in output.splitlines():180 line = line.strip()181 182 m = p1.match(line)183 if m:184 group = m.groupdict()185 rollback_dict = ret_dict.setdefault('id', {}). \186 setdefault(int(group['rollback_id']), {})187 rollback_dict.update({'date': group['date']})188 rollback_dict.update({'time': group['time']})189 continue190 m = p2.match(line)191 if m:192 group = m.groupdict()193 rollback_dict.update({'label': group['label']})194 continue195 m = p3.match(line)196 if m:197 group = m.groupdict()198 rollback_dict.update({'description': group['description']})199 continue200 201 m = p4.match(line)202 if m:203 group = m.groupdict()204 rollback_dict.update({'reload_required': group['reload_required']})205 continue206 m = p5.match(line)207 if m:208 group = m.groupdict()209 install_dict = rollback_dict.setdefault('type', {}). \210 setdefault(group['type'], {})211 install_dict.update({'state': group['state']})212 install_dict.update({'filename_version': group['filename_version']})213 continue214 return ret_dict215class ShowInstallStateSchema(MetaParser):216 """Schema for show install state"""217 schema = {218 'location': {219 Any(): {220 Optional('pkg_state'): {221 Any(): {222 'type': str,223 'state': str,224 'filename_version': str,225 }226 },227 Optional('auto_abort_timer'): str,228 },229 },230 }231class ShowInstallState(ShowInstallStateSchema):232 """Parser for show install state"""233 cli_command = ['show install {state}']234 def cli(self, state="", output=None):235 if output is None:236 # get output from device237 output = self.device.execute(self.cli_command[0].format(state=state))238 # initial return dictionary239 ret_dict = {}240 index = 0241 # initial regexp pattern242 # [ R0 ] Installed Package(s) Information:243 p1 = re.compile(r'^\[ +(?P<location>[\S ]+)\]+\s+\w+ Package\(s\) +Information:$')244 # SMU U bootflash:utah.bm.smu.may15.bin245 # IMG C 10.69.1.0.66982246 p2 = re.compile(r'^(?P<type>\S+) + (?P<state>\w) +(?P<filename_version>\S+)$')247 # Auto abort timer: active on install_activate248 p4 = re.compile(r'^Auto +abort +timer: +(?P<auto_abort_timer>[\S ]+)$')249 for line in output.splitlines():250 line = line.strip()251 # [ R0 ] Installed Package(s) Information:252 m = p1.match(line)253 if m:254 group = m.groupdict()255 location = group['location'].strip()256 location_dict = ret_dict.setdefault('location', {}). \257 setdefault(location, {})258 continue259 # SMU U bootflash:utah.bm.smu.may15.bin260 # IMG C 10.69.1.0.66982261 m = p2.match(line)262 if m:263 group = m.groupdict()264 index += 1265 install_dict = location_dict.setdefault('pkg_state', {}). \266 setdefault(index, {})267 install_dict.update({'type': group['type']})268 install_dict.update({'state': group['state']})269 install_dict.update({'filename_version': group['filename_version']})270 continue271 # Auto abort timer: active on install_activate272 m = p4.match(line)273 if m:274 group = m.groupdict()275 location_dict.update({'auto_abort_timer': group['auto_abort_timer']})276 continue277 return ret_dict278class ShowInstallPackageSMUSchema(MetaParser):279 """Schema for show install state"""280 schema = {281 'package': {282 'name': str,283 'version': str,284 'platform': str,285 'package_type': str,286 Optional('defect_id'): str,287 'package_state': str,288 Optional('supersedes_list'): str,289 Optional('smu_fixes_list'): str,290 'smu_id': int,291 'smu_type': str,292 'smu_compatible_with_version': str,293 Optional('smu_impact'): {294 'package': str,295 'size': int,296 'raw_SHA1_sum': str,297 'header_size': str,298 'package_type': int,299 'package_flags': int,300 'header_version': int,301 'internal_pkg_info': {302 'name': str,303 'build_time': str,304 'release_date': str,305 'boot_architecture': str,306 'route_processor': str,307 'user': str,308 'package_name': str,309 'build': str,310 Optional('card_types'): str,311 },312 },313 },314 }315class ShowInstallPackageSMU(ShowInstallPackageSMUSchema):316 """Parser for show install package SMU/subpkg"""317 cli_command = 'show install package {file_path}'318 def cli(self, file_path="", output=None):319 if output is None:320 output = self.device.execute(self.cli_command.format(file_path=file_path))321 # initial return dictionary322 ret_dict = {}323 # Name: C9800-SW-iosxe-wlc.BLD_POLARIS_DEV_LATEST_20211206_041312_V17_8_0_26.SSA.bin324 p1 = re.compile(r'^Name: +(?P<file_name>.*bin$)')325 # Version: 17.08.01.0.150818.1638769329..Cupertino326 p2 = re.compile(r'Version: +(?P<version>.*$)')327 # Platform: CAT9K328 p3 = re.compile(r'Platform: +(?P<platform>.*$)')329 # Package Type: PKG330 p4 = re.compile(r'Package Type: +(?P<package_type>.*$)')331 # Defect ID: CSCvq24042332 p5 = re.compile(r'Defect ID: +(?P<defect_id>.*$)')333 # Package State: Not Installed334 p6 = re.compile(r'Package State: +(?P<package_state>.*$)')335 # Supersedes List:336 p7 = re.compile(r'Supersedes List: +(?P<supersedes_list>.*$)')337 # SMU Fixes List:338 p8 = re.compile(r'SMU Fixes List: +(?P<smu_fixes_list>.*$)')339 # SMU ID: 1000340 p9 = re.compile(r'SMU ID: +(?P<smu_id>.*$)')341 # SMU Type: reload342 p10 = re.compile(r'SMU Type: +(?P<smu_type>.*$)')343 # SMU Compatible with Version: 17.08.01.0.150818344 p11 = re.compile(r'SMU Compatible with Version: +(?P<smu_compatilble_version>.*$)')345 # SMUImpact:346 # Package: cat9k-wlc.BLD_POLARIS_DEV_LATEST_20211206_041312_V17_8_0_26.SSA.pkg347 p12 = re.compile(r'Package: +(?P<package>.*$)')348 # Size: 657171504349 p13 = re.compile(r'Size: +(?P<size>.*$)')350 # Raw disk-file SHA1sum:351 # 4e739aa1b7f4705bbce4ddddf4afab969ce0a7f0352 p14 = re.compile(r'^Raw disk-file SHA1sum:$')353 p30 = re.compile(r'(^\s*\w+$)')354 # Header size: 1072 bytes355 p15 = re.compile(r'Header size: +(?P<header_size>.*$)')356 # Package type: 0357 p16 = re.compile(r'Package type: +(?P<package_type>.*$)')358 # Package flags: 0359 p17 = re.compile(r'Package flags: +(?P<package_flags>.*$)')360 # Header version: 3361 p18 = re.compile(r'Header version: +(?P<header_version>.*$)')362 # Internal package information:363 # Name: rp_wlc364 p19 = re.compile(r'Name: +(?P<package_name>.*$)')365 # BuildTime: 2021-12-05_21.42366 p20 = re.compile(r'BuildTime: +(?P<build_time>.*$)')367 # ReleaseDate: 2021-12-06_04.53368 p21 = re.compile(r'ReleaseDate: +(?P<release_date>.*$)')369 # BootArchitecture: none370 p22 = re.compile(r'BootArchitecture: +(?P<boot_architecture>.*$)')371 # RouteProcessor: cat9k372 p23 = re.compile(r'RouteProcessor: +(?P<route_processor>.*$)')373 # Platform: CAT9K ---> same regex ------ can we exclude?374 # p24 = re.compile(r'Platform: +(?P<platform>.*$)')375 # User: mcpre376 p25 = re.compile(r'User: +(?P<user>.*$)')377 # PackageName: wlc378 p26 = re.compile(r'PackageName: +(?P<package_name>.*$)')379 # Build: BLD_POLARIS_DEV_LATEST_20211206_041312_V17_8_0_26380 p27 = re.compile(r'Build: +(?P<build>.*$)')381 p28= re.compile(r'CardTypes: +(?P<card_types>.*$)')382 # k = out.splitlines()383 istr = iter(output.splitlines())384 for line in istr:385 line = line.strip()386 m = p1.match(line)387 if m:388 group = m.groupdict()389 install_pkg = ret_dict.setdefault('package', {})390 install_pkg.update({'name': group['file_name']})391 continue392 m = p2.match(line)393 if m:394 group = m.groupdict()395 install_pkg = ret_dict.setdefault('package', {})396 install_pkg.update({'version': group['version']})397 continue398 m = p3.match(line)399 if m:400 group = m.groupdict()401 install_pkg = ret_dict.setdefault('package', {})402 install_pkg.update({'platform': group['platform']})403 continue404 m = p4.match(line)405 if m:406 group = m.groupdict()407 install_pkg = ret_dict.setdefault('package', {})408 install_pkg.update({'package_type': group['package_type']})409 continue410 m = p5.match(line)411 if m:412 group = m.groupdict()413 install_pkg = ret_dict.setdefault('package', {})414 install_pkg.update({'defect_id': group['defect_id']})415 continue416 m = p6.match(line)417 if m:418 group = m.groupdict()419 install_pkg = ret_dict.setdefault('package', {})420 install_pkg.update({'package_state': group['package_state']})421 continue422 m = p7.match(line)423 if m:424 group = m.groupdict()425 install_pkg = ret_dict.setdefault('package', {})426 install_pkg.update({'supersedes_list': group['supersedes_list']})427 continue428 m = p8.match(line)429 if m:430 group = m.groupdict()431 install_pkg = ret_dict.setdefault('package', {})432 install_pkg.update({'smu_fixes_list': group['smu_fixes_list']})433 continue434 m = p9.match(line)435 if m:436 group = m.groupdict()437 install_pkg = ret_dict.setdefault('package', {})438 install_pkg.update({'smu_id': int(group['smu_id'])})439 continue440 m = p10.match(line)441 if m:442 group = m.groupdict()443 install_pkg = ret_dict.setdefault('package', {})444 install_pkg.update({'smu_type': group['smu_type']})445 continue446 m = p11.match(line)447 if m:448 group = m.groupdict()449 install_pkg = ret_dict.setdefault('package', {})450 install_pkg.update({'smu_compatible_with_version': group['smu_compatilble_version']})451 continue452 m = p12.match(line)453 if m:454 group = m.groupdict()455 impact = install_pkg.setdefault('smu_impact', {})456 impact.update({'package': group['package']})457 continue458 m = p13.match(line)459 if m:460 group = m.groupdict()461 impact = install_pkg.setdefault('smu_impact', {})462 impact.update({'size': int(group['size'])})463 continue464 m = p14.match(line)465 if m:466 group = m.groupdict()467 impact = install_pkg.setdefault('smu_impact', {})468 next_line = next(istr)469 m1 = p30.match(next_line.strip())470 if m1:471 impact.update({'raw_SHA1_sum': m1.group(1)})472 # impact.update({'raw_SHA1_sum': str(k[k.index(line)+1])})473 continue474 m = p15.match(line)475 if m:476 group = m.groupdict()477 impact = install_pkg.setdefault('smu_impact', {})478 impact.update({'header_size': group['header_size']})479 continue480 m = p16.match(line)481 if m:482 group = m.groupdict()483 impact = install_pkg.setdefault('smu_impact', {})484 impact.update({'package_type': int(group['package_type'])})485 continue486 m = p17.match(line)487 if m:488 group = m.groupdict()489 impact = install_pkg.setdefault('smu_impact', {})490 impact.update({'package_flags': int(group['package_flags'])})491 continue492 m = p18.match(line)493 if m:494 group = m.groupdict()495 impact = install_pkg.setdefault('smu_impact', {})496 impact.update({'header_version': int(group['header_version'])})497 continue498 m = p19.match(line)499 if m:500 group = m.groupdict()501 impact_info = impact.setdefault('internal_pkg_info', {})502 impact_info.update({'name': group['package_name']})503 continue504 m = p20.match(line)505 if m:506 group = m.groupdict()507 impact_info = impact.setdefault('internal_pkg_info', {})508 impact_info.update({'build_time': group['build_time']})509 continue510 m = p21.match(line)511 if m:512 group = m.groupdict()513 impact_info = impact.setdefault('internal_pkg_info', {})514 impact_info.update({'release_date': group['release_date']})515 continue516 m = p22.match(line)517 if m:518 group = m.groupdict()519 impact_info = impact.setdefault('internal_pkg_info', {})520 impact_info.update({'boot_architecture': group['boot_architecture']})521 continue522 m = p23.match(line)523 if m:524 group = m.groupdict()525 impact_info = impact.setdefault('internal_pkg_info', {})526 impact_info.update({'route_processor': group['route_processor']})527 continue528 m = p25.match(line)529 if m:530 group = m.groupdict()531 impact_info = impact.setdefault('internal_pkg_info', {})532 impact_info.update({'user': group['user']})533 continue534 m = p26.match(line)535 if m:536 group = m.groupdict()537 impact_info = impact.setdefault('internal_pkg_info', {})538 impact_info.update({'package_name': group['package_name']})539 continue540 m = p27.match(line)541 if m:542 group = m.groupdict()543 impact_info = impact.setdefault('internal_pkg_info', {})544 impact_info.update({'build': group['build']})545 continue546 m = p28.match(line)547 if m:548 group = m.groupdict()549 impact_info = impact.setdefault('internal_pkg_info', {})550 impact_info.update({'card_types': group['card_types']})551 continue552 return ret_dict553# ===================================================554# Schema for555# * 'show install version all'556# * 'show install version summary'557# * 'show install version value {value}'558# ===================================================559class ShowInstallVersionSchema(MetaParser):560 """Schema for show install version all"""561 schema = {562 'location': {563 Any(): {564 'version': {565 Any(): {566 'version_extension': str,567 'version_state': str,568 'filename': str,569 'cw_image': str,570 'checksum': str,571 'pkg_list': {572 Any(): {573 'package_type': str,574 'package_name': str,575 'package_state': str,576 },577 },578 },579 },580 },581 },582 }583# ===================================================584# Super Parser for585# * 'show install version all'586# * 'show install version summary'587# * 'show install version value {value}'588# ===================================================589class ShowInstallVersion(ShowInstallVersionSchema):590 """Parser for show install version all"""591 def cli(self, output=None):592 # initial variables593 ret_dict = {}594 index = 0595 # Location: R0596 p1 = re.compile(r'^Location\s*:\s*(?P<location>.*)')597 # Version: 17.10.01.0.160997598 p2 = re.compile(r'Version\s*:\s*(?P<version>.*)')599 # Version Extension: 1655047488600 p3 = re.compile(r'Version Extension\s*:\s*(?P<version_extension>.*)')601 # Version State: Activated & Committed602 p4 = re.compile(r'Version State\s*:\s*(?P<version_state>.*$)')603 # Filename: /flash1/user/cat9k_iosxe.BLD_POLARIS_DEV_LATEST_20220612_143809.SSA.bin604 p5 = re.compile(r'Filename\s*:\s*(?P<filename>.*$)')605 # CW_IMAGE: cat9k_iosxe.BLD_POLARIS_DEV_LATEST_20220612_143809.SSA.bin606 p6 = re.compile(r'CW_IMAGE\s*:\s*(?P<cw_image>.*$)')607 # Checksum: dab9381de08510b901a8f27675f0a711419ccdb1608 p7 = re.compile(r'Checksum\s*:\s*(?P<checksum>.*$)')609 # Package List:610 p8 = re.compile(r'Package List\s*:\s*$')611 # Package Type: IMG612 p9 = re.compile(r'Package Type\s*:\s*(?P<package_type>.*)')613 # Package Name: /flash1/user/cat9k-lni.BLD_POLARIS_DEV_LATEST_20220612_143809.SSA.pkg614 p10 = re.compile(r'Package Name\s*:\s*(?P<package_name>.*)')615 # Package State: Activated & Committed616 p11 = re.compile(r'Package State\s*:\s*(?P<package_state>.*$)')617 for line in output.splitlines():618 line = line.strip()619 m = p1.match(line)620 if m:621 group = m.groupdict()622 location = group['location'].strip()623 location_dict = ret_dict.setdefault('location', {}).setdefault(location, {})624 continue625 m = p2.match(line)626 if m:627 group = m.groupdict()628 version_dict = location_dict.setdefault('version', {}).setdefault(group['version'], {})629 continue630 m = p3.match(line)631 if m:632 group = m.groupdict()633 version_dict.update({'version_extension': group['version_extension']})634 continue635 m = p4.match(line)636 if m:637 group = m.groupdict()638 version_dict.update({'version_state': group['version_state']})639 continue640 m = p5.match(line)641 if m:642 group = m.groupdict()643 version_dict.update({'filename': group['filename']})644 continue645 m = p6.match(line)646 if m:647 group = m.groupdict()648 version_dict.update({'cw_image': group['cw_image']})649 continue650 m = p7.match(line)651 if m:652 group = m.groupdict()653 version_dict.update({'checksum': group['checksum']})654 continue655 m = p8.match(line)656 if m:657 index = 0658 version_dict.setdefault('pkg_list', {})659 m = p9.match(line)660 if m:661 group = m.groupdict()662 index += 1663 pkg_dict = version_dict['pkg_list'].setdefault(index, {})664 pkg_dict.update({'package_type': group['package_type']})665 continue666 m = p10.match(line)667 if m:668 group = m.groupdict()669 pkg_dict.setdefault('package_name', group['package_name'])670 continue671 m = p11.match(line)672 if m:673 group = m.groupdict()674 pkg_dict.setdefault('package_state', group['package_state'])675 continue676 return ret_dict677class ShowInstallVersionAll(ShowInstallVersion):678 """Parser for show install version all"""679 cli_command = 'show install version all'680 def cli(self, output=None):681 if output is None:682 output = self.device.execute(self.cli_command)683 return super().cli(output=output)684class ShowInstallVersionSummary(ShowInstallVersion):685 """Parser for show install version summary"""686 cli_command = 'show install version summary'687 def cli(self, output=None):688 if output is None:689 output = self.device.execute(self.cli_command)690 return super().cli(output=output)691class ShowInstallVersionValue(ShowInstallVersion):692 """Parser for show install version value {value}"""693 cli_command = 'show install version value {value}'694 def cli(self, value=None, output=None):695 if output is None:696 output = self.device.execute(self.cli_command.format(value=value))697 return super().cli(output=output)698class ShowExceptionSchema(MetaParser):699 """Schema for show exception"""700 schema = {701 Optional('patch_version'): str,702 'implement' :str,703 }704class ShowException(ShowExceptionSchema):705 """Parser for show exception706 """707 cli_command = 'show exception'708 def cli(self, output=None):709 if output is None:710 out = self.device.execute(self.cli_command)711 ret_dict = {}712 # !!!Patched Version!!!713 p0 = re.compile(r'!!!Patched Version!!!')714 # show exception not implemented715 p1 = re.compile(r'show exception not implemented')716 for line in out.splitlines():717 line = line.strip()718 # !!!Patched Version!!!719 m = p0.match(line)720 if m:721 ret_dict['patch_version'] = m.group(0)722 continue723 # show exception not implemented724 m = p1.match(line)725 if m:726 ret_dict['implement'] = m.group(0)727 continue...

Full Screen

Full Screen

controller.py

Source:controller.py Github

copy

Full Screen

1# -*- coding: utf-8 -*-2# ***************************************************************************3# * *4# * Copyright (c) 2020 Frank Martinez <mnesarco at gmail.com> *5# * *6# * This program is free software; you can redistribute it and/or modify *7# * it under the terms of the GNU Lesser General Public License (LGPL) *8# * as published by the Free Software Foundation; either version 2 of *9# * the License, or (at your option) any later version. *10# * for detail see the LICENCE text file. *11# * *12# * This program is distributed in the hope that it will be useful, *13# * but WITHOUT ANY WARRANTY; without even the implied warranty of *14# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *15# * GNU General Public License for more details. *16# * *17# * You should have received a copy of the GNU General Public License *18# * along with this program. If not, see <https://www.gnu.org/licenses/>. *19# * *20# ***************************************************************************21from freecad.extman.sources.source_installed import InstalledPackageSource22import FreeCADGui as Gui23from pathlib import Path24import json25from random import randint26import hashlib27from freecad.extman import utils, log_err, tr28from freecad.extman.utils.preferences import ExtManParameters29from freecad.extman.gui.router import Router, route30from freecad.extman.sources.source_cloud import findSource, clearSourcesCache31from freecad.extman.utils.worker import Worker32# +---------------------------------------------------------------------------+33# | Request-Response based actions |34# +---------------------------------------------------------------------------+35def restart(path, session, params, request, response):36 utils.restart_freecad()37def show_install_info(path, session, params, request, response):38 """39 Show information before install40 """41 channel_id = params['channel']42 source = params['source']43 pkg_name = params['pkg']44 session.set_state(installResult=None)45 def job():46 pkg_source = findSource(channel_id, source)47 if pkg_source:48 install_pkg = pkg_source.findPackageByName(pkg_name)49 if install_pkg:50 session.set_state(pkgSource=pkg_source, pkgName=pkg_name, installPkg=install_pkg)51 session.route_to('/CloudSources/Packages/Install')52 response.render_template('index.html')53 Worker(job).start()54def show_uninstall_info(path, session, params, request, response):55 """56 Show information before uninstall57 """58 pkg_name = params['pkg']59 session.set_state(installResult=None)60 def job():61 pkg_source = InstalledPackageSource()62 install_pkg = pkg_source.findPackageByName(pkg_name)63 if install_pkg:64 session.set_state(pkgSource=pkg_source, pkgName=pkg_name, installPkg=install_pkg)65 session.route_to('/CloudSources/Packages/Install')66 response.render_template('index.html')67 Worker(job).start()68def install_package(path, session, params, request, response):69 """70 Install/Update package71 """72 channel_id = params['channel']73 source = params['source']74 pkg_name = params['pkg']75 session.set_state(installResult=None)76 def job():77 pkg_source = findSource(channel_id, source)78 if pkg_source:79 install_pkg = pkg_source.findPackageByName(pkg_name)80 result = pkg_source.install(pkg_name)81 session.set_state(pkgSource=pkg_source, pkgName=pkg_name, installPkg=install_pkg, installResult=result)82 session.route_to('/CloudSources/Packages/Install')83 response.render_template('index.html')84 Worker(job).start()85def uninstall_package(path, session, params, request, response):86 """87 Uninstall package88 """89 pkg_name = params['pkg']90 session.set_state(installResult=None)91 def job():92 pkg_source = InstalledPackageSource()93 install_pkg = pkg_source.findPackageByName(pkg_name)94 result = pkg_source.uninstall(install_pkg)95 session.set_state(pkgSource=pkg_source, pkgName=pkg_name, installPkg=install_pkg, installResult=result)96 session.route_to('/InstalledPackages')97 response.render_template('index.html')98 Worker(job).start()99def update_cloud_source(path, session, params, request, response):100 """101 Update package list of the package source102 """103 pkg_source = findSource(params['channel'], params['name'])104 if pkg_source:105 pkg_source.updatePackageList()106 open_cloud_source(path, session, params, request, response)107def open_cloud_source(path, session, params, request, response):108 """109 List Packages from channel/source110 """111 def job():112 pkg_source = findSource(params['channel'], params['name'])113 session.set_state(pkgSource=pkg_source)114 session.route_to('/CloudSources/Packages')115 response.render_template('index.html')116 Worker(job).start()117def open_cloud(path, session, params, request, response):118 """119 List Cloud channels120 """121 session.route_to('/CloudSources')122 response.render_template('index.html')123def open_installed(path, session, params, request, response):124 """125 List installed packages126 """127 session.set_state(pkgSource=InstalledPackageSource())128 session.route_to('/InstalledPackages')129 response.render_template('index.html')130def set_package_viewmode(path, session, params, request, response):131 ExtManParameters.PackagesViewMode = params['vm']132 response.render_template('index.html')133def open_macro(path, session, params, request, response):134 """135 Open Macro in code editor136 """137 macro = Path(params['macro'])138 if macro.exists():139 Gui.open(str(macro.as_posix()))140 response.html_ok()141def open_workbench(path, session, params, request, response):142 """143 Activate Workbench144 """145 Gui.activateWorkbench(params['workbenchKey'])146 response.html_ok()147def run_macro(path, session, params, request, response):148 """149 Execute macro150 """151 path = Path(params['macro'])152 try:153 Gui.doCommandGui("exec(open(\"{0}\").read())".format(path.as_posix()))154 except Exception as ex:155 log_err(tr("Error in macro:"), path, str(ex))156 response.html_ok()157# +---------------------------------------------------------------------------+158# | Javascript message based actions |159# +---------------------------------------------------------------------------+160def on_form_add_source(data, session):161 result = {162 'status': 'ok',163 'validation': [],164 'message': None165 }166 if not data.get('title'):167 result['status'] = 'error'168 result['validation'].append({'field': 'title', 'message': tr('title is required')})169 if not data.get('url'):170 result['status'] = 'error'171 result['validation'].append({'field': 'url', 'message': tr('url is required')})172 if not data.get('protocol'):173 result['status'] = 'error'174 result['validation'].append({'field': 'protocol', 'message': tr('protocol is required')})175 if result['status'] != 'ok':176 result['message'] = tr('Validation error')177 return result178 name = str(hashlib.sha256(data['url'].encode()).hexdigest())179 sources = json.loads(ExtManParameters.CustomCloudSources)180 sources = [s for s in sources if s['name'] != name]181 if data.get('protocol') in ('github', 'framagit'):182 if not data['url'].endswith('.git'):183 data['url'] = data['url'].strip('/') + '.git'184 source = {185 'name': name,186 'title': data['title'],187 'description': data['description'],188 'git': data['url'],189 'protocol': data.get('protocol', 'github'),190 'type': 'Mod',191 'icon': 'html/img/package_source.svg'192 }193 sources.append(source)194 ExtManParameters.CustomCloudSources = json.dumps(sources)195 clearSourcesCache()196 return {"status": 'ok'}197def on_form_remove_source(data, session):198 name = str(hashlib.sha256(data['url'].encode()).hexdigest())199 sources = json.loads(ExtManParameters.CustomCloudSources)200 sources = [s for s in sources if s['name'] != name]201 ExtManParameters.CustomCloudSources = json.dumps(sources)202 clearSourcesCache()203 return {"status": 'ok'}204# +---------------------------------------------------------------------------+205# | Configuration |206# +---------------------------------------------------------------------------+207def create_router():208 """209 Setup routes210 """211 return Router(212 InstalledPackages=route(any_of=['/InstalledPackages', '/']),213 CloudSources=route(prefix="/CloudSources"),214 CloudSourcesPackages=route(prefix="/CloudSources/Packages"),215 Install=route(exact='/CloudSources/Packages/Install'),216 Uninstall=route(exact='/CloudSources/Packages/Install')217 )218# Functions exposed as actions to WebView219actions = {220 f.__name__: f221 for f in (222 restart,223 show_install_info,224 show_uninstall_info,225 install_package,226 uninstall_package,227 update_cloud_source,228 open_cloud_source,229 open_cloud,230 open_installed,231 set_package_viewmode,232 open_macro,233 open_workbench,234 run_macro235 )236}237# Message handlers238message_handlers = {239 f.__name__: f240 for f in (241 on_form_add_source,242 on_form_remove_source243 )...

Full Screen

Full Screen

main.py

Source:main.py Github

copy

Full Screen

1import os2import sys3import shutil4import zipfile5import platform6import re7if platform.architecture()[0].startswith('32'):8 _ver = '32'9elif platform.architecture()[0].startswith('64'):10 _ver = '64'11curr = os.path.dirname(__file__)12targ = os.path.join(os.path.dirname(sys.executable), 'Scripts')13def copytree(src, dst, symlinks=False, ignore=None):14 if not os.path.exists(dst):15 os.makedirs(dst)16 for item in os.listdir(src):17 s = os.path.join(src, item)18 d = os.path.join(dst, item)19 if os.path.isdir(s):20 copytree(s, d, symlinks, ignore)21 else:22 if not os.path.exists(d) > 1:23 shutil.copy2(s, d)24def install_upx():25 _upx = 'upx-3.95-{}.zip'.format(_ver)26 print('init upx tool: {}'.format(_upx))27 upx = os.path.join(curr, _upx)28 zf = zipfile.ZipFile(upx)29 zf.extractall(path = targ)30 print('upx file in {}'.format(targ))31 print()32def uninstall_upx():33 _targ = os.path.join(targ, 'upx.exe')34 os.remove(_targ)35def install_adb():36 _adb = 'adb-tools.zip'37 print('init adb tool: {}'.format(_adb))38 adb = os.path.join(curr, _adb)39 zf = zipfile.ZipFile(adb)40 zf.extractall(path = targ)41 print('adb file in {}'.format(targ))42 print()43def uninstall_adb():44 _targ = os.path.join(targ, 'adb.exe') ; os.remove(_targ)45 _targ = os.path.join(targ, 'AdbWinApi.dll') ; os.remove(_targ)46 _targ = os.path.join(targ, 'AdbWinUsbApi.dll') ; os.remove(_targ)47def install_tcc():48 _tcc = 'tcc-0.9.27-win{}-bin.zip'.format(_ver)49 print('init tcc tool: {}'.format(_tcc))50 tcc = os.path.join(curr, _tcc)51 zf = zipfile.ZipFile(tcc)52 zf.extractall(path = targ)53 winapi = os.path.join(curr, 'winapi-full-for-0.9.27.zip')54 zf = zipfile.ZipFile(winapi)55 zf.extractall(path = targ)56 fd = 'winapi-full-for-0.9.27'57 finclude = os.path.join(targ, fd, 'include')58 tinclude = os.path.join(targ, 'tcc', 'include')59 copytree(finclude, tinclude)60 shutil.rmtree(os.path.join(targ, fd))61 tccenv = os.path.join(targ, 'tcc')62 copytree(tccenv, targ)63 print('tcc in {}'.format(targ))64 shutil.rmtree(tccenv)65 print()66def install_nasm():67 _nasm = 'nasm-2.14.02-win{}.zip'.format(_ver)68 print('init nasm tool: {}'.format(_nasm))69 nasm = os.path.join(curr, _nasm)70 zf = zipfile.ZipFile(nasm)71 zf.extractall(path = targ)72 tccenv = targ + '\\nasm-2.14.02'73 copytree(tccenv, targ)74 print('nasm in {}'.format(targ))75 shutil.rmtree(tccenv)76 print()77def install_ollydbg():78 _ollydbg = 'ollydbg.zip'79 _targ = os.path.join(os.path.dirname(sys.executable), 'ollydbg')80 print('init ollydbg tool: {}'.format(_ollydbg))81 ollydbg = os.path.join(curr, _ollydbg)82 zf = zipfile.ZipFile(ollydbg)83 zf.extractall(path = _targ)84 print('ollydbg file in {}'.format(_targ))85 print('ollydbg ollydbg can only parse win32 execfile now.')86 print()87def uninstall_ollydbg():88 _targ = os.path.dirname(sys.executable)89 _targ = os.path.join(_targ, 'ollydbg')90 shutil.rmtree(_targ)91def install_procexp():92 _procexp = 'procexp{}.zip'.format(_ver)93 _targ = os.path.join(os.path.dirname(sys.executable), 'procexp')94 print('init procexp tool: {}'.format(_procexp))95 procexp = os.path.join(curr, _procexp)96 zf = zipfile.ZipFile(procexp)97 zf.extractall(path = _targ)98 print('procexp file in {}'.format(_targ))99 print()100def uninstall_procexp():101 _targ = os.path.dirname(sys.executable)102 _targ = os.path.join(_targ, 'procexp')103 shutil.rmtree(_targ)104def install_procmonitor():105 _procmon = 'ProcessMonitor.zip'106 _targ = os.path.join(os.path.dirname(sys.executable), 'procmon')107 print('init procmon tool: {}'.format(_procmon))108 procmon = os.path.join(curr, _procmon)109 zf = zipfile.ZipFile(procmon)110 zf.extractall(path = _targ)111 print('procmon file in {}'.format(_targ))112 print()113def uninstall_procmonitor():114 _targ = os.path.dirname(sys.executable)115 _targ = os.path.join(_targ, 'procmon')116 shutil.rmtree(_targ)117def install_notepadpp():118 _notepadpp = 'notepad++.zip'119 _targ = os.path.dirname(sys.executable)120 print('init notepadpp tool: {}'.format(_notepadpp))121 notepadpp = os.path.join(curr, _notepadpp)122 zf = zipfile.ZipFile(notepadpp)123 zf.extractall(path = _targ)124 print('notepadpp file in {}'.format(_targ))125 config = os.path.join(_targ, 'notepad++', 'config.xml')126 theme = os.path.join(_targ, 'Notepad++', 'themes', 'Obsidian.xml')#.replace('/','\\')127 with open(config, 'r', encoding='utf-8') as f:128 cfgstr = f.read()129 with open(config, 'w', encoding='utf-8') as f:130 a = r'<GUIConfig name="stylerTheme" path="([^>]+)" />'131 b = '<GUIConfig name="stylerTheme" path="{}" />'.format(theme.replace('\\','/'))132 f.write(re.sub(a, b, cfgstr))133 print()134def uninstall_notpadpp():135 _targ = os.path.dirname(sys.executable)136 _targ = os.path.join(_targ, 'Notepad++')137 shutil.rmtree(_targ)138def install(install_pkg='all'):139 if install_pkg == 'upx':140 install_upx()141 elif install_pkg == 'tcc':142 install_tcc()143 elif install_pkg == 'nasm':144 install_nasm()145 elif install_pkg == 'ollydbg':146 install_ollydbg()147 elif install_pkg == 'procexp':148 install_procexp()149 elif install_pkg == 'notepadpp':150 install_notepadpp()151 elif install_pkg == 'procmon':152 install_notepadpp()153 elif install_pkg == 'adb':154 install_adb()155 elif install_pkg == 'all':156 # install_upx() # upx 由于会影响到 pyinstaller 所以将不再默认安装进来157 install_tcc()158 install_nasm()159 install_ollydbg()160 install_procexp()161 install_notepadpp()162 install_procmonitor()163 else:164 print('unknown pkg:{}'.format(install_pkg))165def uninstall(uninstall_pkg):166 if uninstall_pkg == 'notepadpp':167 uninstall_notpadpp()168 elif uninstall_pkg == 'upx':169 uninstall_upx()170 elif uninstall_pkg == 'adb':171 uninstall_adb()172 elif uninstall_pkg == 'ollydbg':173 uninstall_ollydbg()174 elif uninstall_pkg == 'procexp':175 uninstall_procexp()176 elif uninstall_pkg == 'procmon':177 uninstall_procmonitor()178 else:179 print('pkg:{} can not be uninstalled'.format(uninstall_pkg))180def gui():181 q = {}182 l = ['ollydbg','procexp','notepad++','procmon']183 c = os.path.dirname(sys.executable)184 for i in l:185 _c = os.path.join(c, i)186 if os.path.isdir(_c):187 if i == 'ollydbg': fn = 'ollydbg.exe'188 if i == 'procexp': fn = 'procexp{}.exe'.format(_ver)189 if i == 'notepad++': fn = 'notepad++.exe'190 if i == 'procmon': fn = 'Procmon.exe'191 q[i] = os.path.join(_c, fn)192 if not q:193 print('not install any tool in:{}'.format(l))194 import tkinter195 import tkinter.ttk as ttk196 import functools197 root = tkinter.Tk()198 root.title('快捷打开工具')199 for i in q:200 x = lambda i:(os.popen(q[i]), print(q[i]), root.quit())201 x = functools.partial(x, i)202 bt = ttk.Button(root, text=i, command=x)203 bt.pack(side=tkinter.TOP)204 scn_w, scn_h = root.maxsize()205 curWidth = 100206 curHight = 200207 cen_x = (scn_w - curWidth) / 2208 cen_y = (scn_h - curHight) / 2209 size_xy = '%dx%d+%d+%d' % (curWidth, curHight, cen_x, cen_y)210 root.geometry(size_xy)211 root.mainloop()212def notepad():213 c = os.path.join(os.path.dirname(sys.executable), 'notepad++', 'notepad++.exe')214 os.popen(c)215def execute():216 if not platform.platform().lower().startswith('windows'):217 print('only work in windows platform.')218 exit(0)219 argv = sys.argv220 if len(argv) > 1:221 if argv[1] == 'install':222 if len(argv) > 2:223 install(argv[2])224 else:225 install(install_pkg='all')226 if argv[1] == 'uninstall':227 if len(argv) == 2:228 print('pls enter the name of the software you want to uninstall.')229 else:230 uninstall(argv[2])231 else:232 import ii233 print('ii verison: {}.'.format(ii.__version__))234 print('pls use "ii install" to install all tcc,nasm,ollydbg,procexp,procmon,notepadpp.')235 print('(adb,upx not in default install all)')236 print('use "ii install $pkg" install single tool.')237 print('use "igui" start some tools')238 print('use "inote" start notepadpp')239if __name__ == '__main__':240 # install(install_pkg='all')241 # install_procmonitor()242 # gui()243 # install_adb()...

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 autotest 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