def handle_save_dir(file_folder): if file_folder == dst: return 0 if os.path.isdir(file_folder): try: os.mkdir( os.path.join(dst, os.path.relpath(file_folder, src))) except FileExistsError: None files_copied = 0 for sub_file_folder in os.listdir(file_folder): files_copied += handle_save_dir( os.path.normpath( os.path.join(file_folder, sub_file_folder))) return files_copied else: destination_file = os.path.join( dst, os.path.dirname(os.path.relpath(file_folder, src))) copy(file_folder, destination_file) if detailed_output: output( 'create backup: Copied {} to {}.'.format( file_folder, destination_file), filename, file) return 1
def conditional_switch(file, filename, args): if not type(args) is list or (len(args) > 3 or len(args) < 2): output( 'conditional switch: Args is invalid! Must be a list of length 3!', filename, file) return 0, 0 if len(args) < 3: args = args.copy().append(0) if not type(args[1]) is int: output( 'conditional switch: Args is invalid! The second value of the list needs to be an integer!', filename, file) return 0, 0 if len(args) == 3 and not type(args[2]) is int: output( 'conditional switch: Args is invalid! The third value of the list needs to be an integer!', filename, file) return 0, 0 if args[0]: output( 'conditional switch: {} is equivalent to True! Doing {} commands then skipping {}.' .format(args[0], args[1], args[2]), filename, file) return args[2], args[1] else: output( 'conditional switch: {} is equivalent to False. Skipping {} commands.' .format(args[0], args[1]), filename, file) return args[1], 0
def conditional_end(file, filename, args): if args: output( 'conditional end: {} is equivalent to True! Ending the program:'. format(args), filename, file) return -1, 0 else: output( 'conditional end: {} is equivalent to False. Continuing as normal.' .format(args), filename, file) return 0, 0
def sleep(file, filename, args): if not args: return output('sleep: Command cannot run without arguments!', filename, file) if type(args) is int or type(args) is float: time.sleep(args) output('sleep: Slept for {} seconds.'.format(args), filename, file) elif file: output( 'sleep: Could not sleep as the argument {} was not a valid number!' .format(args), filename, file) return
def command_prompt(file, filename, args): if type(args) is list: for arg in args: reply = os.popen(str(arg)).read() while reply.endswith('\n'): reply = reply[:len(reply) - 1] output('command prompt: ' + str(arg) + ': ' + reply, filename, file) else: reply = os.popen(str(args)).read() while reply.endswith('\n'): reply = reply[:len(reply) - 1] output('command prompt: ' + str(args) + ': ' + reply, filename, file)
def delete_file(file, filename, args): def do_deletion(thing, ignore_output=False): if type(thing) is list: for dir in thing: do_deletion(dir) return thing = os.path.normpath(thing) try: if not os.path.exists(thing) and not ignore_output: return output( 'delete file: File or folder {} does not exist. No deletion done.' .format(thing), filename, file) if os.path.isdir(thing): shutil.rmtree(thing) output('delete file: Deleted folder {}.'.format(thing), filename, file) else: os.remove(thing) output('delete file: Deleted file {}.'.format(thing), filename, file) except PermissionError: output( 'delete file: Got permission error while deleting {}!'.format( thing), filename, file) if not args or not (type(args) is list or type(args) is str): return output( 'delete file: Args is invalid! Must be a string or a list containing at least one string!', filename, file) do_deletion(args)
def do_open_page(site): if not type(site) is str: if type(site) is list: for sitez in site: do_open_page(sitez) return return output( 'open webpage: {} is not a string and thus cannot be a valid URL!' .format(site), filename, file) else: if not (site.startswith('http://') or site.startswith('https://') or site.startswith('localhost:') or site[0] in valid_ints): output( 'open webpage: Webpage {} does not start with http://, hhtps://, localhost:, or a number. Adding http:// to the beginning of the URL.' .format(site), filename, file) site = 'http://' + site os.system('start \"\" ' + site)
def conditional_skip(file, filename, args): if not type(args) is list or len(args) != 2: output( 'conditional skip: Args is invalid! Must be a list of length 2!', filename, file) return 0, 0 if not type(args[1]) is int: output( 'conditional skip: Args is invalid! The second value of the list needs to be an integer!', filename, file) return 0, 0 if args[0]: output( 'conditional skip: {} is equivalent to True! Skipping {} commands:' .format(args[0], args[1]), filename, file) return args[1], 0 else: output( 'conditional skip: {} is equivalent to False. Continuing as normal.' .format(args[0]), filename, file) return 0, 0
def do_deletion(thing, ignore_output=False): if type(thing) is list: for dir in thing: do_deletion(dir) return thing = os.path.normpath(thing) try: if not os.path.exists(thing) and not ignore_output: return output( 'delete file: File or folder {} does not exist. No deletion done.' .format(thing), filename, file) if os.path.isdir(thing): shutil.rmtree(thing) output('delete file: Deleted folder {}.'.format(thing), filename, file) else: os.remove(thing) output('delete file: Deleted file {}.'.format(thing), filename, file) except PermissionError: output( 'delete file: Got permission error while deleting {}!'.format( thing), filename, file)
def do_the_writey_thing(filz, writing, detailed_output=False): if type(filz) is list: files_written = 0 for filzz in filz: files_written += do_the_writey_thing(filzz, writing) return files_written if not type(filz) is str: output( '{}: File {} is not a string! Cannot write to file.'.format( 'overwrite file' if overwrite else 'append file', str(filz)), filename, file) return 0 filz = os.path.normpath(filz) try: while not (os.path.isdir(os.path.dirname(filz)) or os.path.dirname(filz) == ''): try: os.mkdir(os.path.dirname(filz)) except FileNotFoundError: dst_temp = os.path.dirname(filz) while not (os.path.isdir(dst_temp) or dst_temp == ''): try: os.mkdir(dst_temp) except FileNotFoundError: dst_temp = os.path.dirname(dst_temp) with open(filz, 'w' if overwrite else 'a') as writ: if type(writing) is list: for i in range(len(writing)): writ.write(str(writing[i])) else: writ.write(writing) output( '{}: Successfully wrote to file {}.'.format( 'overwrite file' if overwrite else 'append file', filz), filename, file) return 1 except PermissionError: output( '{}: Got permission error while trying to write to file {}!'. format('overwrite file' if overwrite else 'append file', filz), filename, file) return 0
def resume_process(file, filename, args): processes = get_processes(args) if type(args) is list: for proc in args: resume_process(file, filename, proc) if len(processes) == 0: output('resume process: Could not find process {}!'.format(args), filename, file) try: for proc in processes: proc.kill() output( 'resume process: Resumed {} (pid: {}).'.format( proc.name(), proc.pid), filename, file) except (psutil.NoSuchProcess, psutil.ZombieProcess, TypeError, AttributeError): pass except psutil.AccessDenied: output( 'resume process: Could not resume process {} (pid: {})! Permission denied!' .format(proc.name(), proc.pid), filename, file)
def simulate_mouse(file, filename, args): method = '''if True: def setpos(x, y): pyautogui.moveTo(x, y) def move(x, y): pyautogui.move(x, y) def click(button, amount=1): mouse_buttons = ['left', 'right', 'middle'] for i in range(amount): pyautogui.click(button=mouse_buttons[button % 3]) def press(button): mouse_buttons = ['left', 'right', 'middle'] pyautogui.mouseDown(button=mouse_buttons[button % 3]) def release(button): mouse_buttons = ['left', 'right', 'middle'] pyautogui.mouseUp(button=mouse_buttons[button % 3]) def scroll(dx, dy = ""): if type(dy) is str: pyautogui.scroll(dx) else: pyautogui.scroll(dy) pyautogui.hscroll(dx) \n''' def command_is_valid(argument): if not ('(' in argument and ')' in argument): return 'Argument {} is invalid! Missing parhenthesis!'.format( argument) method_name = argument[:argument.find('(')].lower() arguments = '[' + argument[argument.find('(') + 1:argument.rfind(')')] + ']' valid_methods = { 'setpos': [2], 'move': [2], 'click': [2, 1], 'press': [1], 'release': [1], 'scroll': [1, 2] } if method_name in valid_methods: try: arguments = literal_eval(arguments) for arg in arguments: if not type(arg) is int: return 'Argument {} is invalid! Not all arguments are ints!'.format( argument) if len(arguments) in valid_methods[method_name]: return True return 'Argument {} is invalid! Inappropriate amount of arguments!'.format( argument) except SyntaxError: return 'Argument {} is invalid! Arguments are not formatted correctly!'.format( argument) else: return 'Argument {} is invalid! {} is not a valid method name!'.format( argument, method_name) if not args or not (type(args) is list or type(args) is str): return output( 'simulate mouse: Args is invalid! Must be a string or a list of strings!', filename, file) elif type(args) is str: command = command_is_valid(args) if command and type(command) is str: return output('simulate mouse: ' + command, filename, file) elif command: exec(method + args[:args.rfind(')') + 1]) else: return output('simulate mouse: Some unknown error occurred.', filename, file) else: commands = [] for cmd in args: command = None if type(cmd) is str: command = command_is_valid(cmd) if command and type(command) is str: return output('simulate mouse: ' + command, filename, file) elif command: commands.append(cmd) else: return output( 'simulate mouse: Some unknown error occurred.', filename, file) else: return output( 'simulate mouse: Argument {} is invalid! Must be a string!' .format(cmd), filename, file) for cmd in commands: method += cmd[:cmd.rfind(')') + 1] + '\n' exec(method)
def log(file, filename, args): if type(args) is list: for thing in args: log(file, filename, str(args)) else: output('log: {}'.format(str(args)), filename, file)
def do_the_copy_thing(src, dst, detailed_output=False, keep_attributes=True): # Recursive call if list if type(src) is list: files_copied = 0 for source in src: if os.path.isdir(source): files_copied += do_the_copy_thing( source, os.path.join(dst, os.path.basename(source)), detailed_output, keep_attributes) else: files_copied += do_the_copy_thing(source, dst, detailed_output, keep_attributes) return files_copied if not type(src) is str: output( 'create backup: Source file/folder {} is not a string! Cannot copy files.' .format(str(src)), filename, file) return 0 if not os.path.exists(src): output( 'create backup: Source file/folder {} does not exist! Cannot copy files.' .format(src), filename, file) return 0 if type(dst) is list: files_copied = 0 for dest in dst: files_copied += do_the_copy_thing(src, dest, keep_attributes) return files_copied # Handle user error if not type(dst) is str: output( 'create backup: Destination folder {} is not a string! Cannot copy files' .format(str(dst)), filename, file) return 0 if os.path.isfile(dst): output( 'create backup: Destination {} is a file, not a folder! Use the command copy file to copy files.' .format(str(dst)), filename, file) return 0 src = os.path.normpath(src) dst = os.path.normpath(dst) if (os.path.isdir(src) and src == dst) or (os.path.isfile(src) and os.path.dirname(src) == dst): output( 'create backup: Source folder and destination folder are one and the same! Copying files would be redundant.', filename, file) # Set copy command copy = shutil.copy2 if keep_attributes else shutil.copy # Make destination folder try: while not (os.path.isdir(dst) or dst == ''): try: os.mkdir(dst) except FileNotFoundError: dst_temp = os.path.dirname(dst) while not (os.path.isdir(dst_temp) or dst_temp == ''): try: os.mkdir(dst_temp) except FileNotFoundError: dst_temp = os.path.dirname(dst_temp) if os.path.isfile(src): copy(src, dst) else: def handle_save_dir(file_folder): if file_folder == dst: return 0 if os.path.isdir(file_folder): try: os.mkdir( os.path.join(dst, os.path.relpath(file_folder, src))) except FileExistsError: None files_copied = 0 for sub_file_folder in os.listdir(file_folder): files_copied += handle_save_dir( os.path.normpath( os.path.join(file_folder, sub_file_folder))) return files_copied else: destination_file = os.path.join( dst, os.path.dirname(os.path.relpath(file_folder, src))) copy(file_folder, destination_file) if detailed_output: output( 'create backup: Copied {} to {}.'.format( file_folder, destination_file), filename, file) return 1 files_copied = 0 for file_folder in os.listdir(src): files_copied += handle_save_dir( os.path.normpath(os.path.join(src, file_folder))) return files_copied except PermissionError: output( 'create backup: Got permission error while copying from {} to {}!' .format(src, dst), filename, file) return 0
def do_nothing(file, filename, args): output('do_nothing: Doing nothing.', filename, file) return
def append_file(file, filename, args, overwrite=False): def do_the_writey_thing(filz, writing, detailed_output=False): if type(filz) is list: files_written = 0 for filzz in filz: files_written += do_the_writey_thing(filzz, writing) return files_written if not type(filz) is str: output( '{}: File {} is not a string! Cannot write to file.'.format( 'overwrite file' if overwrite else 'append file', str(filz)), filename, file) return 0 filz = os.path.normpath(filz) try: while not (os.path.isdir(os.path.dirname(filz)) or os.path.dirname(filz) == ''): try: os.mkdir(os.path.dirname(filz)) except FileNotFoundError: dst_temp = os.path.dirname(filz) while not (os.path.isdir(dst_temp) or dst_temp == ''): try: os.mkdir(dst_temp) except FileNotFoundError: dst_temp = os.path.dirname(dst_temp) with open(filz, 'w' if overwrite else 'a') as writ: if type(writing) is list: for i in range(len(writing)): writ.write(str(writing[i])) else: writ.write(writing) output( '{}: Successfully wrote to file {}.'.format( 'overwrite file' if overwrite else 'append file', filz), filename, file) return 1 except PermissionError: output( '{}: Got permission error while trying to write to file {}!'. format('overwrite file' if overwrite else 'append file', filz), filename, file) return 0 if not args: return output( '{}: Command cannot run without arguments!'.format( 'overwrite file' if overwrite else 'append file'), filename, file) if not type(args) is list or len(args) < 2: return output( '{}: Args is invalid! Must be a list of at least length 2!'.format( 'overwrite file' if overwrite else 'append file'), filename, file) files_written = do_the_writey_thing(args[0], args[1:]) if files_written <= 0: return output( '{}: Wrote to no files.'.format( 'overwrite file' if overwrite else 'append file'), filename, file) elif files_written > 1: return output( '{}: Wrote to {} files.'.format( 'overwrite file' if overwrite else 'append file', files_written), filename, file)
def do_the_copy_thing(src, dst, keep_attributes=True): if not type(src) is str: output( 'copy file: Source file {} is not a string! Cannot copy file.'. format(str(src)), filename, file) return if not os.path.isfile(src): output( 'copy file: Source file {} does not exist! Cannot copy file.'. format(str(src)), filename, file) return if type(dst) is list: for dest in dst: do_the_copy_thing(src, dest, keep_attributes) if not type(dst) is str: output( 'copy file: Destination file/folder {} is not a string! Cannot copy files' .format(str(dst)), filename, file) return 0 if os.path.isdir(dst) and os.path.normpath( os.path.dirname(src)) == os.path.normpath(dst): output( 'copy file: Source file {} is already in the destination folder! Copying would be redundant.' .format(src), filename, file) if os.path.normpath(src) == os.path.normpath(dst): output( 'copy file: Source file and destination file are the same ({})! Copying would be redundant.' .format(os.path.normpath(dst)), filename, file) src = os.path.normpath(src) dst = os.path.normpath(dst) copy = shutil.copy2 if keep_attributes else shutil.copy try: if not os.path.exists(dst): dest = dst if '.' in os.path.basename(dst): dest = os.path.dirname(dst) while not (os.path.isdir(dest) or os.path.dest == ''): try: os.mkdir(dest) except FileNotFoundError: dst_temp = os.path.dirname(dest) while not (os.path.isdir(dst_temp) or dst_temp == ''): try: os.mkdir(dst_temp) except FileNotFoundError: dst_temp = os.path.dirname(dst_temp) copy(src, dst) output('copy file: Copied {} to {}.'.format(src, dst), filename, file) except PermissionError: output( 'copy file: Got permission error while copying from {} to {}!'. format(src, dst), filename, file) return 0
def simulate_keyboard(file, filename, args): standard_keys = [ '`', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '-', '=', 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', '[', ']', '\\', 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', ';', '\'', 'z', 'x', 'c', 'v', 'b', 'n', 'm', ',', '.', '/' ] shifted_keys = { '~': '`', '!': '1', '@': '2', '#': '3', '$': '4', '%': '5', '^': '6', '&': '7', '*': '8', '(': '9', ')': '0', '_': '-', '+': '=', ':': ';', '"': "'", '<': ',', '>': '.', "?": '/' } sub_keys = { 'alt': 'alt', 'lalt': 'altleft', 'altleft': 'altleft', 'ralt': 'altright', 'altright': 'altright', 'backspace': 'backspace', 'capslock': 'capslock', 'caps': 'capslock', 'control': 'ctrl', 'ctrl': 'ctrl', 'lcrtl': 'ctrlleft', 'ctrlleft': 'ctrlleft', 'ctrlright': 'ctrlright', 'delete': 'del', 'del': 'del', 'down': 'down', 'end': 'end', 'enter': 'enter', 'return': 'enter', 'esc': 'esc', 'f1': 'f1', 'f2': 'f2', 'f3': 'f3', 'f4': 'f4', 'f5': 'f5', 'f6': 'f6', 'f7': 'f7', 'f8': 'f8', 'f9': 'f9', 'f10': 'f10', 'f11': 'f11', 'f12': 'f12', 'f13': 'f13', 'f14': 'f14', 'f15': 'f15', 'f16': 'f16', 'f17': 'f17', 'f18': 'f18', 'f19': 'f19', 'f20': 'f20', 'home': 'home', 'insert': 'insert', 'ins': 'insert', 'left': 'left', 'menu': 'home', 'numlock': 'numlock', 'num0': 'num0', 'num1': 'num1', 'num2': 'num2', 'num3': 'num3', 'num4': 'num4', 'num5': 'num5', 'num6': 'num6', 'num7': 'num7', 'num8': 'num8', 'num9': 'num9', 'pagedown': 'pagedown', 'pgdown': 'pagedown', 'pgdn': 'pagedown', 'pageup': 'pageup', 'pgup': 'pageup', 'pause': 'pause', 'break': 'pause', 'printscreen': 'printscreen', 'prntscrn': 'printscreen', 'prtscr': 'printscreen', 'right': 'right', 'scrolllock': 'scrolllock', 'scrlock': 'scrolllock', 'shift': 'shift', 'lshift': 'shiftleft', 'shifteft': 'shiftleft', 'rshift': 'shiftright', 'shiftright': 'shiftright', 'space': 'space', 'spc': 'space', 'tab': 'tab', 'up': 'up', 'windows': 'win', 'win': 'win', 'lwindows': 'winleft', 'lwin': 'winleft', 'rwindows': 'winright', 'rwin': 'winright' } def ktype(message): pyautogui.typewrite(message) def click(key): key = key.replace(' ', '').lower() if key in shifted_keys: key = shifted_keys[key] elif key in sub_keys: key = sub_keys[key] pyautogui.keyDown(key) pyautogui.keyUp(key) def press(key): key = key.replace(' ', '').lower() if key in shifted_keys: key = shifted_keys[key] elif key in sub_keys: key = sub_keys[key] pyautogui.keyDown(key) def release(key): key = key.replace(' ', '').lower() if key in shifted_keys: key = shifted_keys[key] elif key in sub_keys: key = sub_keys[key] pyautogui.keyUp(key) def stroke(sequence): keys = [] now_start_at = 0 if '+' in sequence: sequence = sequence.replace(' ', '').lower() for i in range(sequence.count('+')): end_index = sequence.find('+', now_start_at) key = sequence[now_start_at:end_index] if key in shifted_keys: key = shifted_keys[key] elif key in sub_keys: key = sub_keys[key] keys.append(key) now_start_at = end_index + 1 key = sequence[now_start_at:] if key in shifted_keys: key = shifted_keys[key] elif key in sub_keys: key = sub_keys[key] now_start_at = end_index + 1 keys.append(key) else: sequence = sequence.replace(' ', '').lower() if sequence in shifted_keys: sequence = shifted_keys[sequence] elif sequence in sub_keys: sequence = sub_keys[sequence] keys.append(sequence) for keyz in keys: pyautogui.keyDown(keyz) for keyz in keys: pyautogui.keyUp(keyz) def test_message(arguments): return ktype def test_click(arguments): arguments = arguments.replace(' ', '').lower() if arguments in standard_keys or arguments in shifted_keys or arguments in sub_keys: return click return '"{}" is not a valid key!'.format(arguments) def test_press(arguments): arguments = arguments.replace(' ', '').lower() if arguments in standard_keys or arguments in shifted_keys or arguments in sub_keys: return press return '"{}" is not a valid key!'.format(arguments) def test_release(arguments): arguments = arguments.replace(' ', '').lower() if arguments in standard_keys or arguments in shifted_keys or arguments in sub_keys: return release return '"{}" is not a valid key!'.format(arguments) def test_keystroke(arguments): arguments = arguments.replace(' ', '').lower() if '+' in arguments: now_start_at = 0 for i in range(arguments.count('+')): end_index = arguments.find('+', now_start_at) key = arguments[now_start_at:end_index] if not (key in standard_keys or key in shifted_keys or key in sub_keys): return '"{}" is not a valid keystroke!'.format(arguments) now_start_at = end_index + 1 key = arguments[now_start_at:] if not (key in standard_keys or key in shifted_keys or key in sub_keys): return '"{}" is not a valid keystroke!'.format(arguments) return stroke else: if arguments in standard_keys or arguments in shifted_keys or arguments in sub_keys: return stroke return '"{}" is not a valid keystroke!'.format(arguments) valid_methods = { 'type': test_message, 'click': test_click, 'press': test_press, 'release': test_release, 'stroke': test_keystroke } if not args or not (type(args) is list or type(args) is str): return output( 'simulate keyboard: Args is invalid! Must be a string or a list of strings!', filename, file) elif type(args) is str: if not ('(' in args and ')' in args): return output( 'simulate keyboard: Argument {} is invalid! Missing parhenthesis!' .format(args), filename, file) params = args[args.find('(') + 1:args.rfind(')')] if ((params[0] == '"' and params[len(params) - 1] == '"') or (params[0] == "'" and params[len(params) - 1] == "'")) and len(params) > 1: params = params[1:len(params) - 1] method_name = args[:args.find('(')].lower() if method_name in valid_methods: command = valid_methods[method_name](params) else: return output( 'simulate keyboard: Argument {} is invalid! {} is not a valid method name!' .format(args, method_name), filename, file) if command and type(command) is str: return output( 'simulate keyboard: Argument {} is invalid! '.format(args) + command, filename, file) elif command: command(params) else: return output('simulate keyboard: Some unknown error occurred.', filename, file) else: commands = [] for cmd in args: command = None if type(cmd) is str: if not ('(' in cmd and ')' in cmd): return output( 'simulate keyboard: Argument {} is invalid! Missing parhenthesis!' .format(cmd), filename, file) params = cmd[cmd.find('(') + 1:cmd.rfind(')')] if ((params[0] == '"' and params[len(params) - 1] == '"') or (params[0] == "'" and params[len(params) - 1] == "'")) and len(params) > 1: params = params[1:len(params) - 1] method_name = cmd[:cmd.find('(')].lower() if method_name in valid_methods: command = valid_methods[method_name](params) else: return output( 'simulate keyboard: Argument {} is invalid! {} is not a valid method name!' .format(cmd, method_name), filename, file) if command and type(command) is str: return output( 'simulate keyboard: Argument {} is invalid! '.format( cmd) + command, filename, file) elif command: commands.append([command, params]) else: return output( 'simulate keyboard: Some unknown error occurred.', filename, file) else: return output( 'simulate keyboard: Argument {} is invalid! Must be a string!' .format(cmd), filename, file) for cmd in commands: cmd[0](cmd[1])