def __init__(self, executor): self.executor = executor self.commands = collections.OrderedDict() self.commands[CommandType.FirmwareVersion] = Command( "Check firmware version", Esp8266Ctrl.firmware_version) self.commands[CommandType.ConnectAccessPoint] = Command( "Connect access point", Esp8266Ctrl.connect_access_point) self.commands[CommandType.GetIp] = Command("Get Ip", Esp8266Ctrl.get_ip) self.commands[CommandType.EnableMultipleConnections] = Command( "Enable multiple connections", Esp8266Ctrl.enable_multiple_connections) self.commands[CommandType.ConnectHost] = Command( "Connect host", Esp8266Ctrl.connect_host)
def get_shell_commands(shell_command_line): '''Given a shell command line, get a list of Command objects''' comm_list = shell_command_line.split('&&') cleaned_list = [] for comm in comm_list: cleaned_list.append(Command(comm.strip())) return cleaned_list
def __init__(self, app, parent=None): super(MainWindow, self).__init__(parent) self.app = app; self.setWindowIcon(QIcon('ico/tool.png')) self.setWindowTitle("Instrumenta") self.__config_text_edit__() self.__config_list_view__() self.__config_layout__() self.__config_speech_recognition__() self.command = Command(self) self.edit.setFocus()
class MainWindow(QWidget): def __init__(self, app, parent=None): super(MainWindow, self).__init__(parent) self.app = app; self.setWindowIcon(QIcon('ico/tool.png')) self.setWindowTitle("Instrumenta") self.__config_text_edit__() self.__config_list_view__() self.__config_layout__() self.__config_speech_recognition__() self.command = Command(self) self.edit.setFocus() def __config_text_edit__(self): self.edit = QLineEdit() self.edit.setPlaceholderText("Input search here..") self.edit.installEventFilter(self) def __config_list_view__(self): self.list = QListView(self) model = QStandardItemModel(self.list) for i in range(5): text = 'Item {0}'.format(i + 1) item = QStandardItem(text) item.setCheckable(True) model.appendRow(item) self.list.setModel(model) def __config_layout__(self): layout = QVBoxLayout() layout.addWidget(self.edit) layout.addWidget(self.list) self.setLayout(layout) def __config_speech_recognition__(self): self.thread = sr.ThreadSpeechRecognition() self.thread.signal.sig.connect(self.__set_text_edit_from_thread__) self.thread.start() def __set_text_edit_from_thread__(self, message): self.edit.setText(message) self.__set_command__(message) def closeEvent(self, event): event.ignore() self.hide() def eventFilter(self, widget, event): if widget is self.edit and event.type() == QEvent.KeyPress: key = event.key() text = widget.text() if key == Qt.Key_Return: self.__set_command__(text) if widget is self.edit and event.type() == QEvent.KeyRelease: key = event.key() text = widget.text() print("keyPressed: {0}, texto: {1}".format(key, text)) return False def __set_command__(self, text): self.command.execute(text)
def setUp(self): self.install = Command('apt-get install -y git') self.untar = Command('tar -x -C file tarfile.tar') self.download = Command('wget url') self.remove = Command('apt-get purge git')
class TestClassCommand(unittest.TestCase): def setUp(self): self.install = Command('apt-get install -y git') self.untar = Command('tar -x -C file tarfile.tar') self.download = Command('wget url') self.remove = Command('apt-get purge git') def tearDown(self): del self.install del self.untar del self.download del self.remove def testInstance(self): self.assertEqual(self.install.shell_command, 'apt-get install -y git') self.assertEqual(self.install.name, 'apt-get') # at this point the parser don't know that install is a subcommand self.assertFalse(self.install.subcommand) self.assertEqual(len(self.install.options), 1) self.assertEqual(self.install.options[0][0], '-y') # git isn't an option argument but it should still be in the option # tuple as it comes after -y self.assertEqual(self.install.options[0][1], 'git') self.assertEqual(len(self.install.words), 2) self.assertEqual(self.install.words[0], 'install') self.assertEqual(self.install.words[1], 'git') self.assertEqual(self.install.flags, 0) self.assertFalse(self.install.is_set()) self.assertEqual(self.untar.shell_command, 'tar -x -C file tarfile.tar') self.assertEqual(self.untar.name, 'tar') self.assertFalse(self.untar.subcommand) self.assertEqual(len(self.untar.options), 2) self.assertFalse(self.untar.options[0][1]) self.assertEqual(self.untar.options[1][1], 'file') # there are 2 words - file and tarfile.tar self.assertEqual(len(self.untar.words), 2) self.assertEqual(self.untar.words[0], 'file') self.assertEqual(self.untar.words[1], 'tarfile.tar') self.assertEqual(self.untar.flags, 0) self.assertFalse(self.untar.is_set()) self.assertEqual(self.download.name, 'wget') self.assertFalse(self.download.subcommand) self.assertFalse(self.download.options) self.assertEqual(len(self.download.words), 1) self.assertEqual(self.download.words[0], 'url') self.assertEqual(self.download.flags, 0) self.assertFalse(self.download.is_set()) def testReassignWord(self): # install is a subcommand self.assertTrue(self.install.reassign_word('install', 'subcommand')) self.assertFalse(self.install.reassign_word('install', 'subcommand')) # 'file' is an option argument self.assertTrue(self.untar.reassign_word('file', 'option_arg')) self.assertFalse(self.untar.reassign_word('file', 'option_arg')) # wget has no subcommands self.assertFalse(self.download.reassign_word('safe', 'subcommand')) def testGetOptionArgument(self): # in the case of the install command -y has no options but if it # did it should return 'git' self.assertEqual(self.install.get_option_argument('-y'), 'git') # for the tar command '-C' has the argument 'file' self.assertEqual(self.untar.get_option_argument('-C'), 'file') # for the wget command there are no options so this should # return None self.assertEqual(self.download.get_option_argument('-f'), None) def testFlags(self): # move install subcommand, then set the flag, then check to # see if the command is an install command self.install.reassign_word('install', 'subcommand') self.install.set_install() self.assertTrue(self.install.is_set()) self.assertTrue(self.install.is_install()) # ignore wget self.download.set_ignore() self.assertTrue(self.download.is_set()) self.assertTrue(self.download.is_ignore()) # set apt-get purge as a remove command self.remove.set_remove() self.assertTrue(self.remove.is_set()) self.assertTrue(self.remove.is_remove())
def __init__(self, app_name: str, client): with open(f"./apps/{app_name}/settings.co", 'r') as f: data = f.readlines() self.dict_data = { "name": "", "version": "", "description": "", "permission": [], "command": [], "is_continue": False, } pointer = -1 for line in data: pointer += 1 name_match = re.match(name_comp, line) ver_match = re.match(ver_comp, line) desc_match = re.match(desc_comp, line) permission_match = re.match(permission_comp, line) command_match = re.match(command_comp, line) continue_match = re.match(continue_comp, line) if name_match: self.dict_data['name'] += name_match.groups()[0] continue if ver_match: self.dict_data['version'] += ver_match.groups()[0] continue if desc_match: self.dict_data['description'] += desc_match.group(1).replace("\\", "\n") continue if permission_match: self.dict_data['permission'] += [int(i) for i in permission_match.groups()[0].split(",")] continue if continue_match: if continue_match.group(1) == "True": self.dict_data['is_continue'] = True continue if command_match: groups = command_match.groups() prefix = groups[0] if re.match(command_comp_is_arg, line): arguments = re.match(command_comp_is_arg, line).group(1).split() else: arguments = [] look = "" desc = "" command_pointer = pointer + 1 for l in data[command_pointer:]: look_match = re.match(command_look_comp, l) desc_match = re.match(command_desc_comp, l) if not l.startswith("$"): break if look_match: look = look_match.group(0) continue if desc_match: desc += desc_match.group(0).replace("\\", "\n") continue _command = Command(prefix, arguments, look, desc, ) self.dict_data["command"].append(_command) for key, value in self.dict_data.items(): setattr(self, key, value) if self.is_continue: loader = machinery.SourceFileLoader(app_name, f"./apps/{app_name}/worker.py") app_module = loader.load_module() self.instance = app_module.Worker(client) self.worker = self.instance
def convert_command(input_file, input_folder) -> []: cmd = [] cpath = '' cbody = '' capi = '' caction = '' cname = '' inner_config = False inner_inner_config = False inner_edit = False outer_edit = False rename_flag = False clone_flag = False append_flag = False unselect_flag = False source = input_folder + '/' + input_file if not os.path.isfile(source): logging.error('command: file not found') return cmd for line in fileinput.input(source): line = re.sub(r'"', '', line) if ('#' in line and 'gui-default-policy-columns' not in line): # skip comments continue if 'execute update-now' in line: cpath = 'system/fortiguard/update' cbody = '' capi = 'monitor' caction = 'execute' cname = '' cmd.append(Command(cpath, cbody, capi, caction, cname)) if 'config' in line: line = re.findall(r'\S+', line) if line.__len__() == 2: if inner_config: inner_inner_config = True if cbody == '': cbody = '{' cbody = cbody + ',"' + line[1] + '":[{' else: inner_config = True if cbody == '': cbody = '{' cbody = cbody + ',"' + line[1] + '":{' else: for entry in line: if 'config' in entry: capi = 'cmdb' continue if cpath == '': cpath = entry else: cpath = cpath + '/' cpath = cpath + entry if len(cpath.split("/")) > 2: cpath = cpath.replace("/", ".", 1) if len(cpath.split("/")) > 2: cpath = cpath.replace("/", ".", 1) if 'delete' in line: cname = line.split()[1] caction = 'delete' cmd.append(Command(cpath, cbody, capi, caction, cname)) cname = '' caction = '' if 'rename' in line: rename_flag = True cname = cname + line.split()[3] caction = 'rename' cpath_add = '/' + str(line.split()[1]) cpath = cpath + cpath_add cbody = '{"name":"' + str(cname) + '"}' if 'webfilter/ftgd-local-cat' in cpath: cbody = re.sub(r'name', 'desc', cbody) cmd.append(Command(cpath, cbody, capi, caction, cname)) cname = '' caction = '' cpath = re.sub(str(cpath_add), '', cpath) if 'clone' in line: clone_flag = True cname = cname + line.split()[3] caction = 'clone' cpath_add = '/' + str(line.split()[1]) cpath = cpath + cpath_add cmd.append(Command(cpath, cbody, capi, caction, cname)) cname = '' caction = '' cpath = re.sub(str(cpath_add), '', cpath) if 'show' in line: line = re.findall(r"[\w']+", line) for entry in line: if 'show' in entry: capi = 'monitor' continue if cpath == '': cpath = entry else: cpath = cpath + '/' cpath = cpath + entry if 'edit' in line: rename_flag = False clone_flag = False if outer_edit: inner_edit = True if 'webfilter/profile' in cpath: second = line.split()[1] cbody = cbody + ',"id":"' + str(second) + '"' else: cbody = re.sub(r'":{', '":[{', cbody) else: if not ('firewall/policy' in cpath or 'firewall/local-in-policy' in cpath): cbody = '{"name":"' + str(line.split()[1]) + '"' cname = line.split()[1] caction = 'edit' outer_edit = True if 'append' in line: if not append_flag: cpath = cpath + '/' + cname cbody = '' append_flag = True caction = 'append' first = line.split()[1] second = line.split(first)[1] second = second[1:] cname = first cbody = cbody + '{"name":"' + str(second) + '"}' cbody = re.sub(r'\n+', '', cbody) cmd.append(Command(cpath, cbody, capi, caction, cname)) caction = '' cname = '' cbody = '' if 'unselect' in line: if not unselect_flag: cpath = cpath + '/' + cname cbody = '' unselect_flag = True caction = 'unselect' first = line.split()[1] second = line.split(first)[1] second = second[1:] cname = first + '/' + second cname = re.sub(r'\n+', '', cname) cmd.append(Command(cpath, cbody, capi, caction, cname)) caction = '' cname = '' if ('set' in line) and not ('unset' in line): if cbody == '': cbody = '{' if 'member' in line or 'srcintf' in line or 'dstintf' in line or 'srcaddr' in line or 'dstaddr' in line \ or 'service' in line or 'tunnel-ip-pools' in line \ or ('category' in line and 'category-override' not in line and 'webfilter' not in cpath and 'firewall.service' not in cpath) \ or 'source-interface' in line or 'source-address' in line or 'source-address6' in line \ or ('interface' in line and 'associated-interface' not in line and 'SSL VPN' not in line): # complex object first = line.split()[1] second = line.split(first)[1] second = second[1:] # split all entries to an array second = re.findall(r'\S+', second) third = '' for entry in second: third = third + '{"name":"' + str(entry) + '"},' # special names if 'system/zone' in cpath: third = re.sub(r'"name"', '"interface-name"', third) if 'application/list' in cpath: third = re.sub(r'"name"', '"id"', third) cbody = cbody + ',"' + str(first) + '":[' + str(third) + ']' elif 'vpn.certificate/ca' in cpath: # certificate upload caction = 'upload' capi = 'monitor' destination = input_folder + '/ca.cer' copyfile(source, destination) f = open(destination, 'r') content = f.readlines() f.close() f = open(destination, 'w') need_content = False for subline in content: if 'END CERTIFICATE' in subline: need_content = False subline = re.sub(r'"', '', subline) f.write(subline) if need_content: f.write(subline) if 'BEGIN CERTIFICATE' in subline: need_content = True subline = subline.split('"')[1] f.write(subline) f.close() else: # simple object first = line.split()[1] second = line.split(first)[1] second = second[1:] cbody = cbody + ',"' + str(first) + '":"' + str(second) + '"' if 'webfilter/ftgd-local-cat' in cpath: cbody = re.sub(r'name', 'desc', cbody) if 'unset' in line: if cbody == '': cbody = '{' first = line.split()[1] cbody = cbody + ',"' + str(first) + '":null' if 'next' in line: if cbody != '': cbody = cbody + '}' cbody = re.sub(r'\n+', '', cbody) cbody = re.sub(r',]', ']', cbody) cbody = re.sub(r'{,', '{', cbody) cbody = re.sub(r',{}', '', cbody) if inner_edit: cbody = cbody + ',{' inner_edit = False else: cmd.append(Command(cpath, cbody, capi, caction, cname)) if 'null' in cbody: # "unset" command needs to be executed twice cmd.append(Command(cpath, cbody, capi, caction, cname)) cbody = '' cname = '' caction = '' outer_edit = False if ('end') in line and not ('append' in line): if inner_inner_config: inner_inner_config = False if 'webfilter/profile' in cpath and 'filters' in cbody: cbody = cbody + '}]' elif inner_config: inner_config = False cbody = cbody + '}' if 'application/list' in cpath or 'ips/sensor' in cpath: cbody = cbody + ']' else: if 'null' in cbody: # "unset" command need to be executed twice cmd.append(Command(cpath, cbody, capi, caction, cname)) elif unselect_flag: unselect_flag = False elif append_flag: append_flag = False elif rename_flag: rename_flag = False elif clone_flag: clone_flag = False elif cbody != '': cbody = cbody + '}' cbody = re.sub(r'\n+', '', cbody) cbody = re.sub(r',]', ']', cbody) cbody = re.sub(r'{,', '{', cbody) cmd.append(Command(cpath, cbody, capi, caction, cname)) cpath = '' cbody = '' if not cmd: logging.error('command: error, abort execution') return cmd logging.info('command: converted cli command to rest api command') logging.info('command: parsed ' + str(len(cmd)) + ' commands') return cmd