def shutdown(frames) -> None: # delete all generate files command.run('docker kill gentle') command.run('docker rm gentle') print('\nCombining Frames...') size = frames[0].shape[1], frames[0].shape[0] fourcc = cv2.VideoWriter_fourcc(*'avc1') video = cv2.VideoWriter("generate/cv.mp4", fourcc, 100.0, size) for f in frames: video.write(f) video.release() # delete old output files if os.path.isfile(args.output): os.remove(args.output) print('\nFinishing Up...') export_video = ffmpeg.input('generate/cv.mp4', ) export_audio = ffmpeg.input(args.audio) ffmpeg.concat(export_video, export_audio, v=1, a=1).output(args.output, loglevel='quiet').run() while not os.path.isfile(args.output): pass if not args.no_delete: shutil.rmtree('generate') colorama.init(convert=True) print(f'{Style.RESET_ALL}Done')
def install_virtualenv(app): app_host_app_path = app.host_app_path app_local_repo_path = app.local_repo_path app_virtualenv_path = app.local_virtualenv_path app_virtualenv_activate_path = os.path.join(app_virtualenv_path, 'bin', 'activate') if not os.path.isdir(app_virtualenv_path): os.mkdir(app_virtualenv_path) os.chmod(app_virtualenv_path, 0755) if not os.path.exists(app_virtualenv_activate_path): command.run( ["/usr/bin/virtualenv", "--no-site-packages", app_virtualenv_path], cwd=app_host_app_path ) return command.run_script( """ set -e cd %s source %s pip install -r requirements.txt deactivate """ % (app_local_repo_path, app_virtualenv_activate_path), cwd=app_host_app_path )
def install_virtualenv(app): app_host_app_path = app.host_app_path app_local_repo_path = app.local_repo_path app_virtualenv_path = app.local_virtualenv_path app_virtualenv_activate_path = os.path.join(app_virtualenv_path, 'bin', 'activate') if not os.path.isdir(app_virtualenv_path): os.mkdir(app_virtualenv_path) os.chmod(app_virtualenv_path, 0755) if not os.path.exists(app_virtualenv_activate_path): command.run( ["/usr/bin/virtualenv", "--no-site-packages", app_virtualenv_path], cwd=app_host_app_path) return command.run_script(""" set -e cd %s source %s pip install -r requirements.txt deactivate """ % (app_local_repo_path, app_virtualenv_activate_path), cwd=app_host_app_path)
def check_branch(view, target=clearmake): smartbuilddir="/mot/proj/wibb_bts/daily/tmpsmartbuild/{view}".format(view=view) os.umask(0002) if not os.path.exists(smartbuilddir): os.makedirs(smartbuilddir, 0775) os.utime(smartbuilddir+"/prev_cs_"+target,None) os.utime(smartbuilddir+"/prev_cr_"+target,None) # Compare config spec. If identical, exit 0; else non-zero prevcs=smartbuilddir+"/prev_cs_"+target currcs=smartbuilddir+"/curr_cs_"+target clearcase.ct("catcs -tag {view} > {currcs}".format(view=view,currcs=currcs)) csdiff = filecmp.cmp(prevcs,currcs) # Compare CR list. If identical, exit 0; else non-zero prevcr=smartbuilddir+"/prev_cr_"+target currcr=smartbuilddir+"/curr_cr_"+target command.run(". {scstart} wibb_bts".format(scstart=bmc.config.get("scstart"))) clearcase.ctInView("{mergestat} -a|grep -E '.*yes.*yes.*|.*no.*yes.*' > {currcr}".format(mergestat=bmc.config.get("mergestat"),currcr=currcr)) crdiff = filecmp.cmp(prevcr,currcr) # Update the log entry os.rename(currcs,prevcs) os.rename(currcr,prevcr) # If both config spec and merged CR log are unchanged, then exit 0; else, exit 1. if not (csfiff and crdiff): logger.warn("Nightly build under view {view} for {target} was not kicked off because there's no change to the code or config spec.".format(view=view, target=target)) subject = "Nightly build under view {view} for {target} was not kicked off because there's no change to the code or config spec.".format(view=view, target=target) message = subject utils.sendmail(bmc.config.get("MAILFROM"), mailto, subject, message) raise Exception(message)
def create_user(): """Summary Raises: Exception: Description """ logger.info("Creating user") if config.APP_SFTP_USER in config.FORBIDDEN_USERNAMES: raise Exception("Username value is invalid") create_user_command = [ "useradd", "--no-create-home", "--no-user-group", "--uid", str(config.APP_SFTP_UUID), "--gid", str(config.APP_SFTP_GUID), "-p", str(generate_pass()), config.APP_SFTP_USER, ] command.run(create_user_command)
def _start_iperf(self, remote_sender=True): reverse = "--reverse" if remote_sender else "" iperf_server = f"iperf3 --server" amount = f"-t {self.time}" if not self.data else f"-n {self.data}" local_iperf = f"iperf3 -c {self.remote} {reverse} {amount} -p 5201" cmd.run(iperf_server, host=self.remote).wait(self._timeout) cmd.run(local_iperf).wait(self._timeout)
def start_ssh_server(): """Summary """ logger.info("Starting SSH") start_ssh_command = ["service", "ssh", "start"] command.run(start_ssh_command, quiet=True)
def _start_udp_ping(self): remote_cmd = "~/.local/bin/sUDPingLnx" cmd.run(remote_cmd, host=self.remote).wait(self._timeout) sleep() local_cmd = f"cUDPingLnx -h {self.remote}" cmd.run(local_cmd)
def clone_update_git(git_url, path): if not os.path.exists(os.path.join(path, '.git')): command.run('git clone %s %s' % (git_url, path)) cmds = [ 'git fetch origin', 'git reset --hard origin', ] for cmd in cmds: command.run(cmd, cwd=path)
def pcap_to_csv(pcap_file='./data/pcap.pcap'): """ TODO this is optional """ output_file = os.path.splitext(pcap_file)[0] + '.csv' command = tshark_command(pcap_file, output_file) run(command).wait() return output_file
def mkview(tagorbid, baseline, isDevBranch=False): logger.info("mkview start") logger.info("="*60) if isDevBranch: logger.info("make dev view with bid {bid} based on {baseline}".format(bid=tagorbid, baseline=baseline)) output = cmd.run("{mkview} -bid {bid} -b {baseline}".format(mkview=bmc.config.get('mkview',bid=tagorbid,baseline=baseline))) else: logger.info("make integration view with tag {tag} based on {baseline}".format(tag=tagorbid, baseline=baseline)) output = cmd.run("{mkview} -tag {tag} -share_vw -b {baseline}".format(mkview=bmc.config.get('mkview',tag=tagorbid,baseline=baseline))) logger.info("="*60) logger.info("mkview end")
def pcap_to_csv(pcap_file='./data/pcap.pcap', reparse=False): """ TODO this is optional """ output_file = path.splitext(pcap_file)[0] + '.csv' command = tshark_command(pcap_file, output_file) if reparse or not path.exists(output_file): print(f"regenerating {output_file}") run(command).wait() return output_file
def cleartool(command, *args, **kwargs): logger.info("run cleartool command {command}".format(command=command)) logger.debug("cleartool [{command}] start...".format(command=command)) cleartool = bmc.config.get('cleartool') output = cmd.run("{ct} {command}".format(ct=cleartool, command=command), *args, **kwargs) logger.debug("cleartool [{command}] end.".format(command=command)) return output
def configure_gcloud(): """Summary """ logger.info("Configuring gcloud") auth = [ "gcloud", "auth", "activate-service-account", "--key-file={}".format(config.GCP_SERVICEACCOUNT_KEY_PATH), ] project = ["gcloud", "config", "set", "project", config.GCP_PROJECT_ID] command.run(auth, quiet=True) command.run(project, quiet=True)
def _add_usr(name, uid, gid, groups, shell, mod=False): if not mod: print("Adding user '%s' (%s:%s) ..." % (name, uid, gid)) cmd = 'useradd -r -N -m'.split() else: print("Modifying user '%s' to (%s:%s) ..." % (name, uid, gid)) cmd = 'usermod'.split() if uid: cmd.extend(['-u', str(uid)]) if shell: cmd.extend(['-s', shell]) if gid: cmd.extend(['-g', str(gid)]) else: cmd.extend(['-g', name]) if groups: cmd.extend(['-G', ','.join(groups)]) cmd.append(name) return command.run(cmd)
def add(ppa_name): if ppa_name.strip().startswith('ppa:') or ppa_name.strip().startswith('deb http://ppa.launchpad.net/') or ppa_name.strip().startswith('deb-src http://ppa.launchpad.net/'): success = command.run('sudo add-apt-repository -y "' +ppa_name.strip()+ '"', True) software.update_sources() return True #Always return True because somehow add-apt-repository command always throws an error, even wen successfull else: return False
def derypt_file(infile, outfile, password): cmd = [ 'openssl enc -d -aes-256-cbc', '-in', infile, '-out', outfile, '-pass pass:%s' % password, '-base64' ] # print(" ".join(cmd)) return command.run(" ".join(cmd).split(" "))
def check_update(self): sprout_sh = project_path.join("sprout").join("sprout.sh") try: result = command.run([sprout_sh.strpath, "check-update"]) except command.CommandException as e: result = e needs_update = result.output.strip().lower() != "up-to-date" redis.set("sprout-needs-update", needs_update)
def cleartoolInView(view, command, *args, **kwargs): logger.debug("cleartool setview -exe \"{command}\" {view} start...".format(view=view,command=command)) if not isViewExist(view): raise ViewNotExist(view) cleartool = bmc.config.get('cleartool') output = cmd.run("{ct} setview -exec \"{command}\" {view}".format(ct=cleartool,command=command,view=view), *args, **kwargs) logger.debug("cleartool setview -exe \"{command}\" {view} end.".format(view=view,command=command)) return output
def getViewPath(view): logger.info("get global path for view {view}".format(view=view)) if not isViewExist(view): raise ViewNotExist(view) cleartool = bmc.config.get('cleartool') output = cmd.run("{ct} lsview -long {view}|grep 'Global path'|cut -d' ' -f5".format(ct=cleartool, view=view)) logger.info("Global path: "+output) return output
def __init__(self, command_arg, name=None, env=None, cwd=None, executable='wine', output_to_shell=False, use_log=True, cpu_limit=None): """ Run a program in a separate thread and monitor its state.""" if output_to_shell is True and use_log is True: raise ValueError("output_to_shell and use_log can't both be True") if env is None: env = common.ENV if name is None: #name = command_arg.split()[0].split('\\')[-1] if type(command_arg) in (str, unicode): programs.isolate_executable_from_command(command_arg) else: name = command_arg[0] try: name = util.get_program_name(util.wintounix(name)) except (IOError, TypeError): name = '' self.name = name print(executable) if executable is not None and len(executable): if executable == 'wine' and 'WINE' in env: executable = common.ENV['WINE'] if type(command_arg) in (__builtin__.list, tuple): command_arg = [executable] + command_arg else: command_arg = "%s '%s'" % (executable, command_arg) print(executable) if cpu_limit is not None and type(cpu_limit) is int and cpu_limit > 0: if common.which('taskset'): command_arg = ['taskset', str(cpu_limit)] + command_arg print("Limiting process to {0} CPUs.".format(cpu_limit)) else: print(("Couldn't limit process to {0} CPUs, " + "taskset isn't installed." ), file=sys.stderr) self.has_standard_output = True self.prefix = env.get('WINEPREFIX', None) self.child = command.run(command_arg, name = name, env = env, cwd = cwd, output_to_shell = output_to_shell, use_logfiles = use_log ) self.pid = self.child.pid self.start_time = self.child.start_time if use_log is True: self._create_info_file() RUNNING_PROGRAMS[self.child.log_filename_base] = self # Clean up RUNNING_PROGRAMS update_list()
def install(packages): cmd = 'apt-get -y install'.split() cmd.extend(packages) env = { 'DEBIAN_FRONTEND': 'noninteractive', } return command.run(cmd, env=env)
def install_repository(repository_url, repository_filename="addon_repo.zip"): repo_zip_file_path = "/tmp/" + repository_filename.strip() filesystem.delete(repo_zip_file_path) try: f = urllib2.urlopen(repository_url.strip()) except: log.error("Repository " + repository_url + " could not be downloaded", stack()[0][3]) return False data = f.read() with open(repo_zip_file_path, "wb") as code: code.write(data) if not os.path.exists(repo_zip_file_path): log.error("Repository file" + repo_zip_file_path + " does not exist", stack()[0][3]) return False if not command.run("unzip -o " + repo_zip_file_path + " -d " + config.xbmc_addons_dir): log.error("Repository file" + repo_zip_file_path + " could not be extracted", stack()[0][3]) return False return command.run("sudo chown -R " + config.xbmc_user + ":" + config.xbmc_user + " " + config.xbmc_addons_dir)
def init(): command.run('docker kill gentle') command.run('docker rm gentle') command.run('docker run --name gentle -p 8765:8765 lowerquality/gentle', False) # wait until image is running while 'Up' not in command.run('docker ps'): pass
def get_file_sha256sum(file): cmd = [ 'sha256sum', file, ] ret = command.run(cmd) if ret.exit != 0: raise Exception("Error") return ret.output
def upload_file(file_path: str): """Summary Args: file_path (str): Description """ buckets = config.APP_GCS_BUCKETS.split(",") logger.info(f"Uploading file at path : {file_path}") for bucket in buckets: relative_path = os.path.relpath(file_path, config.APP_LANDING_INGEST_DIR) upload_command = [ "/usr/bin/gsutil", "cp", file_path, f"gs://{os.path.join(bucket, relative_path)}", ] if not helpers.is_tmp(file_path): command.run(upload_command, quiet=True) else: logger.info("Skipping temp file - {}", {"path": file_path})
def create_users(): """Summary Raises: Exception: Description """ logger.info("Creating user") for user, _ in config.PROJECT_CONFIG["USERS"].items(): if user in config.FORBIDDEN_USERNAMES: raise Exception(f"Username {user} value is invalid") create_user_command = (f"useradd --no-create-home --no-user-group " f"--gid {config.APP_SFTP_GUID} {user}") password = open( os.path.join(config.APP_SECRETS_DIR, config.PROJECT_CONFIG["APP"]["NAME"], 'users', user, 'password'), 'r').read().split('\n')[0] change_password_command = f"yes {password} | passwd {user}" change_user_directory_command = ( f"usermod -d {os.path.join(config.APP_LANDING_DIR, user)} {user}") command.run(create_user_command) command.run(change_password_command, quiet=True) command.run(change_user_directory_command)
def _add_grp(name, gid, mod=False): if not mod: print("Adding group '%s' (%s) ..." % (name, gid)) cmd = 'groupadd -r'.split() else: print("Modifying group '%s' to (%s) ..." % (name, gid)) cmd = 'groupmod'.split() if gid: cmd.extend(['-g', str(gid)]) cmd.append(name) return command.run(cmd)
def checknfsmount(builserver,mountpoint,host=None): """ Check if directory is already mounted or not True if directory is mounted """ cmd_out = command.run("mount",hosts=host) if cmd_out['exit'] != 0: return False for line in cmd_out['stdout'].split('\n'): if ((builserver in line) and (mountpoint in line)): return True return False
def graph_data(pcap="./data/2020-05-09/mlc2_bbr_10/mlc2.pcap", output_dir="tcptrace_graphs/"): run(f"tcptrace -N -R -T --output_dir={output_dir} {pcap}").wait() cur_dir = os.getcwd() os.chdir(output_dir) for f in os.listdir(): filename, extension = os.path.splitext(f) if extension == ".xpl": run(f"xpl2gpl {f}").wait() run(f"gnuplot -e \"set terminal png size 1200,900; set output '{filename}.png'\" {filename}.gpl" ).wait() os.chdir(cur_dir)
def get_active(key_word): ppas_text = command.run('grep -hi "^deb.*launchpad" /etc/apt/sources.list /etc/apt/sources.list.d/*') ppas = [] ppa_lines = ppas_text.split('\n') for line in ppa_lines: ppa_parts = line.split(' ') if len(ppa_parts) == 4: ppa_url_parts = ppa_parts[1].split('/') ppa_user_name = ppa_url_parts[-3] ppa_name = ppa_url_parts[-2] ppas.append('ppa:'+ppa_user_name+'/'+ppa_name) sorted_ppas = sorted(list(set(ppas))) if key_word.strip() == '': return sorted_ppas else: filtered_ppas = [] for entry in sorted_ppas: if key_word in entry: filtered_ppas.append(entry) return filtered_ppas
def __init__(self, command_arg, name=None, env=None, cwd=None, executable='winetricks', output_to_shell=False, use_log=True): """ Run a program in a separate thread and monitor its state.""" if env is None: env = common.ENV if name is None: #name = command_arg.split()[0].split('\\')[-1] name = command_arg[0] self.name = name print(executable) if executable is not None and len(executable): if type(command_arg) in (__builtin__.list, tuple): command_arg = [executable, '-q', '--verbose'] + command_arg else: command_arg = "%s -q --verbose '%s'" % (executable, command_arg) print(executable) self.has_standard_output = False self.prefix = env.get('WINEPREFIX', None) self.child = command.run(command_arg, name = name, env = env, cwd = cwd, output_to_shell = output_to_shell, use_logfiles = use_log ) self.pid = self.child.pid self.start_time = self.child.start_time self.packages_already_installed = [] self.status_download_procentage = 0 if use_log == True: self._create_info_file() RUNNING_PROGRAMS[self.child.log_filename_base] = self # Clean up RUNNING_PROGRAMS update_list()
def test_inputsize(urlnum): global oj global urls global config url = urls[urlnum] if not url.startswith("http"): url = "https://atcoder.jp/contests/" + url time.sleep(wait) generate(generate_args(url.split("/")[-1]), config) comp(comp_args(), config) ok = 1 testcase_num = 1 while 1: try: output = run(run_args(testcase_num, url.split("/")[-1]), config) except: break assert output == test_str + "\n" testcase_num += 1 testcase_num -= 1 assert testcase_num > 0
def test_run_debug(self, capsys): def debug_print(line): print(line) response = command.run(['ls', test_path], debug=debug_print) out, err = capsys.readouterr() assert response.exit == 0 assert response.output == b"""\ __pycache__ test_command.py""" # Pyton 2 vs 3 handles strings in different ways if sys.version_info[0] is 2: assert out == b"""\ __pycache__ test_command.py """ elif sys.version_info.major is 3: assert out == "b'__pycache__'\nb'test_command.py'\n" assert err == ''
def tshark_all(): pcaps = [local for local, _, _ in all_pcaps()] procs = [] for pcap_file in pcaps: output_file = path.splitext(pcap_file)[0] + '.csv' if path.exists(output_file): os.remove(output_file) print('parsing pcap ', pcap_file) proc = run(tshark_command(pcap_file, output_file)) procs.append((output_file, proc)) if (len(procs) > 4): print("waiting for current 4 to finish") for output_file, proc in procs: proc.wait() procs.clear() for name, proc in procs: print('waiting for ', name) proc.wait()
def nfsmount(server,sourcemntpt,targetmntpt,host=None): """ Do nfs mount, @args: server, sourcemntpt, targetmntpt @return: True: if successfully mounted False: if not mounted 1. check if already mounted or not. """ if checknfsmount(server,sourcemntpt,host=host) == True: return True systemdata = systeminfo.hostuname() if systemdata['platfrom'] == 'Linux': cmd = "mount -t vxfs {}:{} {}".format(server,sourcemntpt,targetmntpt) if systemdata['platfrom'] == 'AIX': cmd = "mount -V vxfs {}:{} {}".format(server,sourcemntpt,targetmntpt) if systemdata['platfrom'] == 'SunOS': cmd = "mount -V vxfs {}:{} {}".format(server,sourcemntpt,targetmntpt) if systemdata['platfrom'] == 'HP-UX': cmd = "mount -V vxfs {}:{} {}".format(server,sourcemntpt,targetmntpt) cmd_out = command.run(cmd,hosts=host) if cmd_out['exit'] != 0: return False return True
def main(argv=None): global logger, tmp_dir, module_dir module_dir = os.path.split(__file__)[0] args = parse_args(argv) if args.debug: coloredlogs.install(level='DEBUG') logger.debug("Command arguments: %s" % args) cleanup.init() tmp_dir = __create_tempdir() # Create workdir (usually ~/.trellosa, used for caching etc.) # Assumes that no previous code must write to it. if not os.path.exists(args.workdir): logger.debug('Creating working directory %s' % args.workdir) os.makedirs(args.workdir) # Execute the specified command try: result = command.run(args, tmp_dir) except KeyboardInterrupt: logger.critical("\nUser interrupt. Quitting...") return 10 if len(threading.enumerate()) > 1: logger.info("Waiting for background threads to finish") while len(threading.enumerate()) > 1: logger.debug("Remaining threads: %s" % threading.enumerate()) time.sleep(2) return result
def shutdown(dimensions) -> None: # delete all generate files command.run('docker kill gentle') command.run('docker rm gentle') # delete old output files if os.path.isfile(args.output): os.remove(args.output) print('\nFinishing Up...') dimensions = dimensions.split(':') for a in range(len(dimensions)): dimensions[a] = math.ceil(float(dimensions[a]) / 2) * 2 ffmpeg = f'ffmpeg -r 100 -i generate/images/%d.png -i {args.audio} -vf scale={dimensions[0]}:{dimensions[1]} -c:v libx264 -pix_fmt yuv420p {args.output}' command.run(ffmpeg) while not os.path.isfile(args.output): pass if not args.no_delete: shutil.rmtree('generate') colorama.init(convert=True) print(f'{Style.RESET_ALL}Done')
def _start_tcpdump(self): local = f"sudo tcpdump -Z $USER -i {LOCAL_DEVICE} -s 96 port 5201 -w {self.local_pcap}" remote = f"sudo tcpdump -Z $USER -i {REMOTE_DEVICE} -s 96 port 5201 -w pcap.pcap" cmd.run(remote, host=self.remote).wait(self._timeout) cmd.run(local) sleep(5)
import command command.run()
def _cleanup(self): # procs = ['tcpdump', 'cUDPingLnx', 'sUDPingLnx', 'iperf3'] procs = ['tcpdump', 'iperf3'] kill_cmd = 'pkill ' + '; pkill '.join(procs) + ';' cmd.run(kill_cmd).wait(self._timeout) cmd.run(kill_cmd, host=self.remote).wait(self._timeout)
import os import sys sys.path.append(os.path.dirname(__file__) + '/../Libraries') import colorama colorama.init() import command # These register things import environment import repository import inventory import standard import system import select import local import misc if __name__ == '__main__': sys.exit(command.run(sys.argv[1:]))
def test_run_failure(self): with py.test.raises(command.CommandException): command.run(['ls', 'blahblah'])
def run(self, argv): if argv and argv[0] in ('-h', '--help'): print self.description return if os.environ.get('REQUEST_METHOD'): # We're probably in a CGI environment sys.stdout = sys.stderr os.environ['PASTE_DEFAULT_QUIET'] = 'true' # Maybe import cgitb or something? if '_' not in os.environ: print "Warning: this command is intended to be run with a #! like:" print " #!/usr/bin/env paster exe" print "It only works with /usr/bin/env, and only as a #! line." # Should I actually shlex.split the args? filename = argv[-1] args = argv[:-1] extra_args = [] else: filename = os.environ['_'] extra_args = argv[:] args = [] while extra_args: if extra_args[0] == filename: extra_args.pop(0) break args.append(extra_args.pop(0)) vars = {'here': os.path.dirname(filename), '__file__': filename} f = open(filename) lines = f.readlines() f.close() options = {} lineno = 1 while lines: if self._exe_section_re.search(lines[0]): lines.pop(0) break lines.pop(0) lineno += 1 pre_options = [] options = args for line in lines: lineno += 1 line = line.strip() if not line or line.startswith('#'): continue if self._section_re.search(line): break if '=' not in line: raise command.BadCommand('Missing = in %s at %s: %r' % (filename, lineno, line)) name, value = line.split('=', 1) name = name.strip() value = value.strip() if name == 'require': pkg_resources.require(value) elif name == 'command' or name == 'add': options.extend(shlex.split(value)) elif name == 'plugin': options[:0] = ['--plugin', value] else: value = value % vars options.append('--%s=%s' % (name.replace('_', '-'), value)) os.environ['PASTE_CONFIG_FILE'] = filename options.extend(extra_args) command.run(options)
def main(): command.run()
def test_run_timeout_failure(self): with py.test.raises(command.CommandException): command.run(['sleep', '2'], timeout=1)
def restore_backup(backup_file): filePath = config.xbmc_backups_dir + backup_file filesystem.delete_directory(config.xbmc_home_dir) if command.run('tar -zxf "' + filePath + '" -C "' + config.home_dir, True): return True return False
def _copy_remote_pcap(self): command = f"scp {self.remote}:pcap.pcap {self.remote_pcap}" cmd.run(command).wait(self._timeout)
def setup_tc(self): return cmd.run(self.cmd(), host=self.host)
def shutdown(): return command.run('sudo shutdown now -h -q', True)
def test_run_ls(self): response = command.run(['ls', test_path]) assert response.exit == 0 assert response.output == b"""\
def reboot(): return command.run('sudo reboot now -q', True)
def test_run_timeout_successs(self): command.run(['sleep', '1'], timeout=10)
def backup_config(): fileName = str(int(time.time())) + "_xbmc_backup.tar.gz" backupPath = config.xbmc_backups_dir + fileName if command.run('tar -czf "' + backupPath + '" -C "' + config.home_dir + '" ".xbmc"', True): return True return False
def test_run_command_string(self): response = command.run('ls %s' % test_path) assert response.exit == 0 assert response.output == b"""\
from __future__ import print_function import command import os.path import logging logging.basicConfig(level=logging.DEBUG, format='%(message)s') print("Go go gadget") response = command.run(['python', os.path.join(os.path.dirname(__file__), 'sleep.py')], debug=logging.debug) print("\nOutput:") print(response.output) print("\nReturn Code:") print(response.exit)
def zip_contents(zip_file_name, zip_folder_list, password=None): if password is not None: zip_me = "zip -P" + password + " -r " + zip_file_name + " " + "FOLDER1/" + " " + "FOLDER2" else: zip_me = "zip -r " + zip_file_name + " " + "FOLDER1/" + " " + "FOLDER2" command.run(zip_me)