def after_tag(context, tag): if tag == "mac_teardown": cmd = str('''osascript -e 'tell application "System Preferences" to quit' ''') output = CmdHelper.run(cmd) LogHelper.info(output) # cmd = str('''osascript -e 'tell application "MozyPro Restore" to quit' ''') # output = CmdHelper.run(cmd) if tag.lower() == 'web_teardown': pass if tag.lower() == 'macfryr_teardown': cmd = str('sudo pkill "Mozy Restore Manager"') output = CmdHelper.run(cmd) LogHelper.info(output) if tag.lower() == 'winfryr_teardown': close_fryr = 'taskkill /F /IM MozyRestoreManager.exe' output = CmdHelper.run(close_fryr) LogHelper.info(output) close_ff = 'taskkill /F /IM firefox.exe' output = CmdHelper.run(close_ff) LogHelper.info(output) if tag.lower() == 'winfryr_lsh_teardown': close_lsh_fryr = 'taskkill /F /IM MozyLshRestoreManager.exe' try: output = CmdHelper.run(close_lsh_fryr) except Exception: LogHelper.info(output)
def public_restore_flow(encrypt_type='default', encrypt_key=None): # If multiple restore jobs found, then automation will select the latest job to do the restore. # Below try catch is to process the multi-restore job scenarios try: MacFryrElement({'AXRole': 'AXRow'}, -1, 10).left_click() LogHelper.info("Multiple restore jobs found, automation will select the latest job to do the restore.") MacFryrElement({'AXRole': 'AXButton', 'AXIdentifier': '_NS:29'}).click() except: LogHelper.info("Only one restore job found, automation will do restore with the default job.") MacFryrElement({'AXRole': 'AXRadioButton', 'AXDescription': 'selectNewLocationRadio'}).click() MacFryrElement({'AXValue': 'Documents'}).left_click() MacFryrElement({'AXIdentifier': '_NS:64'}).mouse_click({'AXValue': 'auto_restore'}) MacFryrElement({'AXRole': 'AXButton', 'AXIdentifier': '_NS:97'}).click() MacFryrElement({'AXRole': 'AXButton', 'AXIdentifier': '_NS:29'}).click() if encrypt_type == 'pkey': MacFryrElement({'AXRole': 'AXTextField', 'AXIdentifier': '_NS:502'}).force_send(encrypt_key) MacFryrElement({'AXRole': 'AXButton', 'AXIdentifier': '_NS:29'}).click() elif encrypt_type == 'ckey' or encrypt_type == 'rkey': command = 'cp ' + os.path.dirname(os.path.dirname(__file__)) + '/' + encrypt_key + ' ' + ConfigAdapter.get_installer_path() CmdHelper.run(command) MacFryrElement({'AXRole': 'AXButton', 'AXIdentifier': '_NS:495'}).click() MacFryrElement({'AXIdentifier': '_NS:81'}).click() MacFryrElement({'AXTitle': 'Macintosh HD'}).click() MacFryrElement({'AXIdentifier': '_NS:64'}).mouse_click({'AXValue': 'fryr_installer'}) MacFryrElement({'AXRole': 'AXButton', 'AXIdentifier': '_NS:97'}).click() MacFryrElement({'AXIdentifier': '_NS:64'}).mouse_click({'AXValue': encrypt_key}) MacFryrElement({'AXRole': 'AXButton', 'AXIdentifier': '_NS:97'}).click() MacFryrElement({'AXRole': 'AXButton', 'AXIdentifier': '_NS:29'}).click() MacFryrElement({'AXRole': 'AXButton', 'AXIdentifier': '_NS:29'}).click()
def end_process(self, dest, pattern, build): processname = self.get_processname(dest, pattern, build) if processname: if self.check_process_by_name(processname): tskill_cmd = "taskkill /f /t /im %s" % (processname) print tskill_cmd CmdHelper.run(tskill_cmd)
def download_and_install(cls, build, job): volume_name = cls.get_subdir() if volume_name is not None: CmdHelper.run("diskutil eject '" + volume_name + "'") LogHelper.info( "Prepare download Mozy Restore Manager from jenkins, build number is " + job) jh = JenkinsHelper(GLOBAL_CONFIG["JENKINS"]["URL"], GLOBAL_CONFIG["JENKINS"]["USERNAME"], GLOBAL_CONFIG["JENKINS"]["KEY"]) dest = ConfigAdapter.get_installer_path('MACFRYR') LogHelper.info('Clean up existing files') for file in FileHelper.find_file(dest, '*'): LogHelper.debug('Delete file %s' % file) FileHelper.delete_file(file) pattern = 'mozy-fryr' packages = jh.download_packages(jh.get_packages(job, build, pattern), dest=dest) TARGET_APP = '/Applications/Mozy Restore Manager.app' if os.path.exists(TARGET_APP): shutil.rmtree(TARGET_APP) image_path = packages[0] mount_cmd = 'sudo hdiutil attach {package}'.format(package=image_path) CmdHelper.run(mount_cmd) volume_name = cls.get_subdir() ORIGIN_APP = '/Volumes/' + volume_name + '/Mozy Restore Manager.app' shutil.copytree(ORIGIN_APP, TARGET_APP)
def start_fb(cls): if PlatformHelper.is_mac(): fb_binary_dir = os.path.join(cls.config_path, cls.package_name.split(".tar.gz")[0]) os.chdir(fb_binary_dir) cmd = "./filebeat -c filebeat.yml &" output = os.system(cmd) if PlatformHelper.is_Linux(): cmd = "service filebeat start" output = CmdHelper.run(cmd) if PlatformHelper.is_win(): cmd = "sc start filebeat" # This is to make sure filebeat service can be started after install time.sleep(1) output = CmdHelper.run(cmd) # service = "Get-WmiObject -ClassWin32_Service-Filter name='filebeat'" # service.StartService() # service.StopService() LogHelper.info("start filebeat result %s" % output) return output
def is_fb_running(cls): result = False if PlatformHelper.is_Linux(): cmd = "service filebeat status" cmd_output = CmdHelper.run(cmd) LogHelper.debug(cmd_output) if cmd_output.find("running") >= 0: result = True if PlatformHelper.is_mac(): cmd = "ps aux | grep 'filebeat -c' | grep -v 'grep'" output = CmdHelper.run(cmd) if output.find("filebeat") >= 0: result = True if PlatformHelper.is_win(): cmd = "sc query filebeat" output = CmdHelper.run(cmd) if output.find("RUNNING") >= 0: result = True if result: LogHelper.debug("filebeat is running") else: LogHelper.info("filebeat is not running") return result
def kill_fb(cls): """ kill file beat process :return: """ result = False if PlatformHelper.is_mac() or PlatformHelper.is_Linux(): cmd = "ps aux | grep 'filebeat -c' | grep -v 'grep'" output = CmdHelper.run(cmd) process_id = output.split()[1] kill_fb_cmd = "kill -9 %s" % process_id output = CmdHelper.run(kill_fb_cmd) if PlatformHelper.is_win(): cmd = "sc stop filebeat" output = CmdHelper.run(cmd) LogHelper.debug(output) if cls.is_fb_running(): LogHelper.error( "filebeat service CAN NOT be stopped successfully.") else: LogHelper.info("filebeat service is stopped") result = True return result
def disable_uac(): cmd = "REG ADD HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System /v EnableLUA /t REG_DWORD /d 0 /f" CmdHelper.run(cmd) cmd = "REG ADD HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System /v ConsentPromptBehaviorAdmin /t REG_DWORD /d 0 /f" CmdHelper.run(cmd) print "Disable UAC"
def kill_process(self, process_name): if process_name == "status": processname = self.statusapp elif process_name == "config": processname = self.configapp close_cmd = 'taskkill /F /IM %s' % (processname) print close_cmd CmdHelper.run(close_cmd)
def get_os_release_info(os_type): r""" get os release info for worker :param os_type: :return: """ if os_type.upper() == 'LINUX': os_info_file = '/etc' is_deb_based = os.path.isfile( os.path.join(os_info_file, 'os-release')) is_rpm_based = os.path.isfile( os.path.join(os_info_file, 'system-release')) if is_deb_based: cmd = "cat /etc/os-release" output = CmdHelper.run(cmd) for line in output.splitlines(): regex = re.match(r'(.*)=(.*)', line) if regex and regex.group(1) == "ID": id = regex.group(2).replace('"', '') if regex and regex.group(1) == "VERSION_ID": version_id = regex.group(2) version_id = version_id.replace('"', '').replace('.', "_") result = '{id}_{version_id}'.format(id=id, version_id=version_id) return result.upper() elif is_rpm_based: cmd = "cat /etc/system-release" output = CmdHelper.run(cmd) result = output.replace(" ", "_").replace('(', '').replace(')', '').rstrip() return result.upper() else: result = 'unknown versions' return result.upper() if os_type.upper() == 'MAC': cmd = 'sudo sw_vers' output = CmdHelper.run(cmd) for line in output.splitlines(): regex = re.match("ProductVersion:\s+(.*)", line) if regex: version = regex.group(1) product_version = version.strip().lstrip().replace( '.', '_') return product_version if os_type.upper() in ("WINDOWS", 'WIN'): # result = '{release}_{version}'.format(release=PlatformHelper.get_system()+PlatformHelper.get_release(), version=PlatformHelper.get_version()) return platform.platform().replace('.', '_').replace('-', '_').upper()
def create_file(path, overwrite=True, size=1024, content="random"): """ method to create test files """ basedir = os.path.dirname(path) FileHelper.create_directory(basedir) if PlatformHelper.is_Linux(): # or PlatformHelper.is_mac(): cmd = 'sudo chmod -R 777 {path}'.format(path=basedir) CmdHelper.run(cmd) if content == "random": FileHelper._create_file_random(path, overwrite, size, 1024) else: FileHelper._create_file_pattern(path, overwrite, size, content)
def __kill_security_agent(): is_sa_exist = False find_cmd = 'lsappinfo find name=SecurityAgent' output = CmdHelper.run(find_cmd).replace('\n','') wait_time = 0 while (not output) and wait_time<60: time.sleep(5) wait_time += 5 output = CmdHelper.run(find_cmd) if wait_time>=60: print 'timeout' if output: cmd = MacController.prefix_for_sudo() + 'sudo -S killall -9 "SecurityAgent"' CmdHelper.run(cmd)
def remove_tree(dir, topdown=True): for root, dirs, files in os.walk(dir, topdown=False): for name in files: filename = os.path.join(root, name) os.chmod(filename, stat.S_IWUSR) os.remove(filename) for name in dirs: try: os.removedirs(os.path.join(root, name)) except OSError as e: if PlatformHelper.is_Linux( ): # or PlatformHelper.is_mac(): CmdHelper.run('sudo rm -rf {path}'.format( path=os.path.join(root, name)))
def create_backupset(self, targetFolder, backupsetname="automation", extension="NoExtension"): # Generate a backup set file based on a template LogHelper.info("Generating template file") backupset_file = os.path.join(os.getcwd(), "..", extension) guid = Windows_Cli.get_Guid() with open(backupset_file, 'w') as f: f.write("SET\n") f.write("name: %s\n" % backupsetname) f.write("guid: %s\n" % guid) f.write("selected: 1\n") f.write("excluded: 0\n") f.write("lock_rules: 0\n") f.write("lock_selection: 0\n") f.write("\n") f.write("PATHS\n") f.write("include: %s\n" % targetFolder) f.write("\n") if not (extension == "NoExtension"): f.write("RULES\n") f.write("extension \"%s\"\n" % extension) f.write("\n") LogHelper.info("Create backupset") cmd = '"' + self.mozyutil + '"' + " /addbackupset " + backupset_file print cmd result = CmdHelper.run(cmd) LogHelper.info("Create backupset %s successfully." % backupset_file) return result
def delete_worker(cls, worker_name, queue_name): # celery control add_consumer queue exchange direct rkey # $ celery control -d w1.e.com add_consumer queue_name cmd = 'celery control -A {app} -d {worker_name} cancel_consumer {queue_name}'.format( app=cls.celery_app, worker_name=worker_name, queue_name=queue_name) output = CmdHelper.run(cmd) return output
def exe_cmd(cls, param=None): cmd = "{} {}".format(cls._mozyutil, cls._command_name) if param is not None: cmd = cmd + param LogHelper.info("MozyUtil CMD: {cmd}".format(cmd=cmd)) return CmdHelper.run(cmd)
def is_rpm_dist(): result = False cmd = "rpm --version" output = CmdHelper.run(cmd) if not re.match(r".*not found.*", output): result = True return result
def is_debian_dist(): result = False cmd = "dpkg --version" output = CmdHelper.run(cmd) if not re.match(re.compile('.*not found.*'), output): result = True return result
def __run_continuous(cls, mode): cmd = "{} {}".format(cls._mozyutil, cls._command_name) if mode == cls.CONTINUOUS: cmd += ' on' else: cmd += ' off' return CmdHelper.run(cmd)
def create_directory(path, recursive=True): """ :param path: directory path :return: path """ path = os.path.abspath(path) sub_path = os.path.dirname(path) if not os.path.exists(sub_path) and recursive: FileHelper.create_directory(sub_path) if not os.path.exists(path): try: os.mkdir(path) except OSError: if PlatformHelper.is_Linux(): # or PlatformHelper.is_mac(): cmd = 'sudo mkdir -p {path}'.format(path=path) CmdHelper.run(cmd) return path
def is_client_running(self): cmd = 'lsappinfo find bundleID={bundleId}'.format( bundleId=self.bundleid) output = CmdHelper.run(cmd) if output.find('ASN') >= 0: result = True else: result = False return result
def check_process_by_name(name): result = False pid = CmdHelper.run( 'ps aux | grep "{name}" | grep -v grep'.format(name=name)) if pid: result = True return result
def check_process_by_name(processname): result = False processname = processname.replace('.exe', '') cmd = "tasklist|find \"%s\"" % (processname) search_result = CmdHelper.run(cmd) print search_result if search_result: result = True return result
def get_mode(cls): cmd = "{} {}".format(cls._mozyutil, cls._command_name) output = CmdHelper.run(cmd) result = None if output.lower().lstrip().rstrip() == 'on': result = cls.CONTINUOUS elif output.lower().lstrip().rstrip() == 'off': result = cls.ON_DEMAND return result
def activate_auto(self, username): cmd = '"' + self.mozyutil + '"' + " /autoactivate " + username print cmd result = CmdHelper.run(cmd) if "Error" in result: LogHelper.error("Activation Failed with an Error: %s" % result) return False else: return True
def activate_productkey(self, email, password, productkey): cmd = '"' + self.mozyutil + '"' + " /activate " + email + " " + password + " /productkey " + productkey print cmd result = CmdHelper.run(cmd) if "Error" in result: LogHelper.error("Activation Failed with an Error: %s" % result) return False else: return True
def get_root_volume_name(): cmd = 'diskutil info / | grep "Volume Name"' output = CmdHelper.run(cmd) volume_name = '' import re match = re.findall(r':(.*)', output) if match: volume_name = match[0].strip().lstrip() return volume_name
def clean_all(self): entities = FileHelper.find_file(self.app_support_dir, '*') for entry in entities: if entry.find('backup.pid') >= 0: continue if entry.find('restore') >= 0: continue if entry.find('network') >= 0: continue cmd = MacController.prefix_for_sudo( ) + 'sudo -S rm -rf "%s"' % entry CmdHelper.run(cmd) # cache_db_path = os.path.join(self.cache_dir, self.cache_db) # cmd = "sudo rm -rf '{path}'".format(path=cache_db_path) # CmdHelper.run(cmd) self.restart_mozypro_pid()
def activate_keyless(self, email, password, encryption_type="customkeytext", key=""): cmd = '"' + self.mozyutil + '"' + " /keylessactivate /email " + email + " /pass " + password + " /customkeytext " + key print cmd result = CmdHelper.run(cmd) if "Error" in result: LogHelper.error("Activation Failed with an Error: %s" % result) return False else: return True
def get_version(self): cmd = '{codename} --version'.format(codename=self.codename) output = CmdHelper.run(cmd) if output.find('command not found') >= 0: version = 0 # not installed else: version = output.split('.')[-1] time.sleep(5) return int(version)