def rm_all(): rmid_list = get_total_rmid_list() for each in rmid_list: try: rm(each) except Exception as reason: print("Failed because of: " + str(reason))
def subopen(args, stdin=None, shell=False, cwd=None, env=None): temp = None pid = None close_fds = True rstrip = True try: if stdin is not None and isstring(stdin): temp = tempfile() write(temp, stdin) stdin = open(temp) args = tolist(args) for i, arg in enumerate(args): if not isinstance(arg, int): if PY3: args[i] = str(arg) # python3 else: args[i] = __builtin__.unicode(arg) # python2 if not env: env = os.environ.copy() process = subprocess.Popen(args, stdin=stdin, stderr=subprocess.PIPE, stdout=subprocess.PIPE, close_fds=close_fds, shell=shell, cwd=cwd, env=env, universal_newlines=False # , # startupinfo=startupinfo#, # creationflags=creationflags ) pid = process.pid stdoutdata, stderrdata = process.communicate() if PY3: # python3. process.communicate returns bytes stdoutdata = str(stdoutdata, "utf-8") # stdoutdata stderrdata = str(stderrdata, "utf-8") # stderrdata # rstrip if rstrip and stdoutdata: stdoutdata = stdoutdata.rstrip() if rstrip and stderrdata: stderrdata = stderrdata.rstrip() returncode = process.returncode return (returncode, stdoutdata, stderrdata) # raise CalledProcessError(returncode,args,err) # if returncode!=0: # raise CalledProcessError(returncode,args,stderrdata) # return stdoutdata finally: try: if pid: os.killpg(pid, signal.SIGTERM) except Exception: pass # print(format_exc()) rm(temp)
def test_rm(self, mock_os, mock_path): mock_path.isfile.return_value = False rm('any path') self.assertFalse(mock_os.remove.called, ''' Tried to remove when file not present.''') # make the file 'exist' mock_path.isfile.return_value = True rm('any path') mock_os.remove.assert_called_with('any path')
def test_rm(self, mock_os, mock_path): # mock_path就是patch过后的`os.path`,mock_os就是patch过后的`os` #需要注意顺序 #指定`mock_path.isfile`的返回值False mock_path.isfile.return_value = False rm("any path") #测试mock_os.remove有没有被调用 self.assertFalse(mock_os.remove.called, "Failed to not remove the file if not present.") # 指定`mock_path.isfile`的返回值为True mock_path.isfile.return_value = True rm("any path") mock_os.remove.assert_called_with("any path")
def play_video_audio_intent(self, message): #the full utterance can be accessed like this: message.data.get('utterance') #Remember that search_query.rx file from earlier? If we want the contents of the query we supplied we can get it using message.data.get("search_query") #self.speak_dialog(message.data.get("search_query")) ytURL = self.getResults(message.data.get("search_query")) #It takes a moment for the command to be processed so probably best to prompt them! self.speak_dialog("downloading") #Get Sultan running that command sultan = Sultan() #first we remove any existing output file: rm("/tmp/output.wav") #ytURL = "https://www.youtube.com/watch?v=IPXIgEAGe4U" #double underscores are needed for the syntax here - they're an equivalent of a hyphen sultan.youtube__dl("-x --audio-format wav -o '/tmp/output.%(ext)s' " + ytURL).run() #Then we use the audio service to play our file: self.audio_service.play('file:///tmp/output.wav')
def osascript(applescript, flags=None): """osascript applescript code or file """ args = ["osascript"] if applescript and isinstance(applescript, list): applescript = "\n".join(applescript) temp = programfile = None if applescript and os.path.exists(applescript): programfile = applescript else: temp = programfile = tempfile() write(temp, applescript) try: if flags: args += ["-s", flags] if programfile: args.append(programfile) returncode, stdout, stderr = subopen(args) return (returncode, stdout, stderr) finally: rm(temp)
def runTests(r): sys.path.insert(0, success) code = "runProcess(success, 'theTests.spyReporter', 'False', noGrepArgs)" result = runProcess(success, "theTests.spyReporter", "False", noGrepArgs) testState = getTestState() successFiles = set(os.listdir(success)) passed = (result.code == 0 and result.stdout is None and result.stderr is None and len(testState.tests) == 1 and testState.after.__name__ != "noop" and testState.before.__name__ != "noop" and "after-ran.txt" in successFiles and "before-ran.txt" in successFiles and spyReporter.lastCalledState.testState is testState) if not passed: print(result.stderr) r.addError(code) rm([ path.join(success, "after-ran.txt"), path.join(success, "before-ran.txt"), ]) sys.path.pop(0) return r
def mv(src, dst): import cp import rm cp.cp(src, dst) rm.rm(src)
def main(): """ main function """ parser = argparse.ArgumentParser(description='this is to get IP address for lynis audit only') parser.add_argument('-env', '--environment', required=True, help='The cloud on which the test-suite is to be run', choices=['aws', 'gcp', 'azure']) parser.add_argument('-aip', '--audit_ip', required=False, help='The IP for which lynis Audit needs to be done .... by default tries root/Administrator if username not provided') parser.add_argument('-u', '--user_name', required=False, help='The username of the user to be logged in,for a specific user') parser.add_argument('-pem', '--pem_file', required=False, help='The pem file to access to AWS instance') parser.add_argument('-p', '--password', required=False, action='store_true', dest='password', help='hidden password prompt') parser.add_argument('-pId', '--project_id', help='Project ID for which GCP Audit needs to be run. Can be retrivied using `gcloud projects list`') parser.add_argument('-az_u', '--azure_user', required=False, help='username of azure account, optionally used if you want to run the azure audit with no user interaction.') parser.add_argument('-az_p', '--azure_pass', required=False, help='username of azure password, optionally used if you want to run the azure audit with no user interaction.') parser.add_argument('-o', '--output', required=False, default="cs-audit.log", help='writes a log in JSON of an audit, ideal for consumptions into SIEMS like ELK and Splunk. Defaults to cs-audit.log') parser.add_argument("-w", "--wipe", required=False, default=False, action='store_true', help="rm -rf reports/ folder before executing an audit") parser.add_argument('-n', '--number', required=False, help='Retain number of report to store for a particular environment and user/project.') args = parser.parse_args() # set up logging log = logger.setup_logging(args.output, "INFO") log.info("starting cloud security suite v1.0") if args.number and args.wipe == True: print("Warning you can't use -w or -n flag at same time") exit(1) elif args.number: try: int(args.number) except Exception as _: print("Please provide a number for -n option only. ") print("EXITTING!!") exit(1) if args.password: password = getpass() if args.wipe: log.info("wiping reports/ folder before running") rm.rm("reports/") if args.environment == 'gcp': from modules import gcpaudit if not args.project_id: print ("Please pass project ID for the GCP Audit") print ("Exiting !!!") exit(0) else: log.info("running gcp audit") gcpaudit.gcp_audit(args.project_id) log.info("completed gcp audit") elif args.environment == 'aws': from modules import awsaudit from modules import merger from modules import localaudit if args.audit_ip: if not(args.user_name): args.user_name = None if not(args.pem_file): args.pem_file = None if not(args.password): password = None log.info("running aws local audit") localaudit.local_audit(args.audit_ip, args.user_name, args.pem_file, password) log.info("completed aws local audit") exit(0) else: log.info("running aws audit") awsaudit.aws_audit() merger.merge() log.info("completed aws audit") elif args.environment == 'azure': if args.azure_user and args.azure_pass: print("using azure credentials passed via cli") subprocess.call(['az', 'login', '-u', args.azure_user, '-p', args.azure_pass]) else: print("azure authentication required") subprocess.call(['az', 'login']) log.info("running azure audit") from modules import azureaudit azureaudit.azure_audit() log.info("completed azure audit") if args.number > 0 and args.wipe == False: from modules import retainnumberofreports retainnumberofreports.retain_reports(args.environment, int(args.number)) exit(0)
def test_rm(self, mock_os): rm("any path") mock_os.remove.assert_called_with("any path")
''' Check if the file really contains the pattern AXXXXXX... X should all be integers ''' try: [isinstance(int(x), numbers.Number) for x in anb_small[1:]] # The A-Nb. evt has 'a' instead of 'A' self.anb = anb_small.replace('a', 'A') except ValueError: self.anb = None self.path = mkpath(self.filename, wd=source_dir) # ### Do the job ### ''' # emptying directories, for debug purpose - TODO add option rm(to_keep_dir) rm(to_trash_dir) ''' # recreate .gitkeep touch([mkpath(".gitkeep", wd=to_keep_dir)]) images = [Picture(i) for i in ls_source_dir] # NOTE debug logs = mkpath("logs") debug = open(logs, 'w') ''' for item in images: debug.write("%s\n" % item.filename)
def test_rm(self, mock_os): rm('any path') # test that rm called os.remove with the right parameters mock_os.remove.assert_called_with('any path')
def test_rm(self): # remove the file rm(self.tmpfilepath) # test that it was actually removed self.assertFalse(os.path.isfile(self.tmpfilepath), "Failed to remove the file.")