Esempio n. 1
0
    def start_rsync(self):
        rsync_conf = """
uid=root
gid=root
use chroot=yes
og file=/dev/null
[%s]
    path=%s
    read only=no
    write only=yes
""" % (RSYNC_SERVER_NAME, conf.MOUNT_POINT_DIR)

        f = open(conf.RSYNC_CONF_PATH, "w")
        try:
            f.write(rsync_conf)
        finally:
            f.close()
        rsync_cmd = [
            "rsync", "--daemon",
            "--config=%s" % (conf.RSYNC_CONF_PATH), "--no-detach"
        ]
        rsync_cmd.append("--address=%s" % (self.listen_ip))
        rsync_cmd.append("--port=%s" % (self.rsync_port))
        #self._rsync_popen = subprocess.Popen(rsync_cmd, stderr=subprocess.PIPE, close_fds=True)
        self._rsync_popen = Command(rsync_cmd)
        self._rsync_popen.start()
        self.logger.info("started rsync, pid=%s" % (self._rsync_popen.pid))
        time.sleep(1)
Esempio n. 2
0
 def flatten(self, args):
     new_symbol = [x for x in args if not self.is_constant(x.command)]
     # TODO - betterized flattening - taking into account types?
     new_const = ''.join([x.command for x in args if self.is_constant(x.command)])
     if new_const:
         c = Command()
         c.command = new_const
         new_symbol.append(c)
     return new_symbol
Esempio n. 3
0
def initDB(database):
    """Create the tables if they don't exist, and set up the connection for
    the command class"""

    createTablesIfNecessary(database)
   
    # Initialize the required variables
    commandInitializer = Command(None)
    commandInitializer.connectToDB(database)
Esempio n. 4
0
File: xen.py Progetto: wwq0327/vps
 def uptime(domain):
     cmd = "xm uptime %s | grep %s " % (domain, domain)
     c = Command(cmd)
     status, out = c.read_from()
     if status == 0:
         return out.split()[2]
     elif re.match(r"^.*Domain '.+?' does not exist.*$", out):
         return None
     else:
         raise CommandException(cmd, msg=out, status=status)
Esempio n. 5
0
 def flatten(self, args):
     new_symbol = [x for x in args if not self.is_constant(x.command)]
     # TODO - betterized flattening - taking into account types?
     new_const = ''.join(
         [x.command for x in args if self.is_constant(x.command)])
     if new_const:
         c = Command()
         c.command = new_const
         new_symbol.append(c)
     return new_symbol
Esempio n. 6
0
    def enter_directory(self, directory: str) -> DirectoryChangeResult:
        """Change to the specified directory relative to the project root. The current directory must be at the
        project root."""
        res = DirectoryChangeResult()

        if not self._has_exited_initial_directory:
            Command("cd ..").exec()
            res.increment_dir_out()

            self._has_exited_initial_directory = True

        Command(f"cd {directory}").exec()
        res.increment_dir_in(directory_count(directory))

        return res
Esempio n. 7
0
 def register_command(self,
                      cid,
                      message,
                      data,
                      commander,
                      status='NEW',
                      schedule=None,
                      result=''):
     com = Command(cid,
                   message,
                   data,
                   commander,
                   status=status,
                   schedule=schedule,
                   result=result)
     if com.cid == 0:
         reason = 'Invalid command'
     elif com.cid == -1:
         reason = 'You are not authorized to perform this command.'
     elif com.cid == -2:
         reason = 'Invalid schedule time. Please respect the given format and make sure that the date is in the future'
     elif com.cid == -3:
         reason = 'Not enough arguments provided for command'
     else:
         return self.insert_command(com), 'Error within the database'
     util.log(reason)
     return -1, reason
Esempio n. 8
0
    def __init__(self):
        self.config_file = "c:/test-av/conf/vmware.conf"
        self.conf = Config(self.config_file)
        self.cmd = Command(self.conf.path, self.conf.host, self.conf.user,
                           self.conf.passwd)

        self.dst_dir = "c:/Users/avtest/Desktop"
Esempio n. 9
0
    def start_rsync(self):
        rsync_conf = """
uid=root
gid=root
use chroot=yes
og file=/dev/null
[%s]
    path=%s
    read only=no
    write only=yes
""" % (RSYNC_SERVER_NAME, conf.MOUNT_POINT_DIR)

        f = open(conf.RSYNC_CONF_PATH, "w")
        try:
            f.write(rsync_conf)
        finally:
            f.close()
        rsync_cmd = ["rsync", "--daemon", "--config=%s" %
                     (conf.RSYNC_CONF_PATH), "--no-detach"]
        rsync_cmd.append("--address=%s" % (self.listen_ip))
        rsync_cmd.append("--port=%s" % (self.rsync_port))
        #self._rsync_popen = subprocess.Popen(rsync_cmd, stderr=subprocess.PIPE, close_fds=True)
        self._rsync_popen = Command(rsync_cmd)
        self._rsync_popen.start()
        self.logger.info("started rsync, pid=%s" % (self._rsync_popen.pid))
        time.sleep(1)
Esempio n. 10
0
    async def consumer(self, message: str):
        print(message)
        tiny_crap = json.loads(message)
        if tiny_crap["tc"] == "userlist":
            for user in tiny_crap["users"]:
                self.accounts.update({user["handle"]: user["nick"]})
        if tiny_crap["tc"] == "joined":
            self.handle = tiny_crap["self"]["handle"]

        if tiny_crap["tc"] == "join":
            self.accounts.update({tiny_crap["handle"]: tiny_crap["nick"]})
        if tiny_crap["tc"] == "quit":
            self.accounts.pop(tiny_crap["handle"])
        if tiny_crap["tc"] == "ping":
            await self.pong()
        if tiny_crap["tc"] == "msg":
            # check for a command, decorators are optional you can do it manually overriding msg in cog
            for prefix in self.settings["bot"]["prefixes"]:
                # if prefix match continue
                if tiny_crap["text"].startswith(prefix):
                    await self.attempt_command(Command(data=tiny_crap))

        if tiny_crap["tc"] == "password":
            await self.password()
        # runs cog events
        for type in constants.T_OBJECTS:
            if tiny_crap["tc"] == type:
                for cog in self.cogs:
                    await getattr(cog, type.lower())(tiny_crap)
Esempio n. 11
0
    def __init_commands(self):
        self._logger.info('Loading commands.')
        importdir.do('commands', globals())
        if self._config.has_option('bot', 'extra_commands_dir'):
            extra_commands_dir = self._config.get('bot', 'extra_commands_dir')
            if extra_commands_dir and os.path.exists(extra_commands_dir):
                self._logger.info('Added %s to command load path.', extra_commands_dir)
                importdir.do(extra_commands_dir, globals())

        disabled_commands = []
        try:
            if self._config.has_option('bot', 'disabled_commands'):
                disabled_commands = json.loads(self._config.get('bot', 'disabled_commands'))
        except ValueError as ex:
            self._logger.exception(ex)

        for command in Command.__subclasses__():
            if command.name not in disabled_commands:
                self.__enable_command(command)
            else:
                del command

        self._logger.info('Enabled commands: %s.', list(self.commands.keys()))
        if disabled_commands:
            self._logger.info('Disabled commands: %s.', disabled_commands)
Esempio n. 12
0
    def load(self):
        first = True
        try:
            for line in self.input_file:
                if first and line.startswith('#'):
                    continue
                line = line.strip()
                if self.is_blank(line):
                    continue
                command = Command(free_format=self.free_format,
                                  tight=self.tight)
                command.parse(line)
                self.threads.code(0).append(command)

        except ParseError, e:
            print >> sys.stderr, e
            return False
Esempio n. 13
0
    def load(self):
        first = True
        try:
            for line in self.input_file:
                if first and line.startswith('#'):
                    continue
                line = line.strip()
                if self.is_blank(line):
                    continue
                command = Command(free_format=self.free_format,
                                  tight=self.tight)
                command.parse(line)
                self.threads.code(0).append(command)

        except ParseError, e:
            print >> sys.stderr, e
            return False
Esempio n. 14
0
    def run(self, flags: FlagSet):
        build_cmd = "cargo build"

        is_local = flags.get("-d", "--dev")
        if is_local is None:
            build_cmd += " --release"

        Command(build_cmd).exec()
Esempio n. 15
0
 def __init__(self):
     self.name = "unsaved"
     self.uri = None
     self.command = Command()
     self.notes = None
     self.state = None
     self.log = None
     self.run_time = None
Esempio n. 16
0
    def __init__(self):
        """ Configure command interface through Config class
		"""
        self.config_file = "c:/test-av/conf/vmware.conf"
        self.conf = Config(self.config_file)
        #
        # you can redefine the Command class providing vmrun full path:
        # self.cmd = Command("vmrun full path")
        #
        # TODO:
        #	- Command class with one argument
        self.cmd = Command(self.conf.path, self.conf.host, self.conf.user,
                           self.conf.passwd)

        # full paths of script neede for update
        self.netENScript = "c:/Users/avtest/Desktop/EnableIF.bat"
        self.netDISScript = "c:/Users/avtest/Desktop/DisableIF.bat"
        self.updScript = "C:/Users/avtest/Desktop/AVUpdate.bat"
Esempio n. 17
0
    def enter_root_directory(current_directory: str) -> DirectoryChangeResult:
        """Enters the root repository directory."""
        res = DirectoryChangeResult()

        back_cd = ""
        for i in range(directory_count(current_directory)):
            back_cd += "../"

        Command(f"cd {back_cd}").exec()
        return res
Esempio n. 18
0
 def listen(self, command: Command):
     # create recognizer and mic instances
     recognizer = sr.Recognizer()
     microphone = sr.Microphone()
     stop = Preference().getInstance().get_stop()
     reload = Preference().getInstance().get_reload()
     while True:
         time.sleep(0.2)
         print("Listening")
         guess = self.recognize_speech_from_mic(recognizer, microphone)
         if guess == stop:
             print("Stopping Program")
             Analtyics.getInstance().print()
             break
         if guess == reload:
             Preference().getInstance().load()
             command.refresh()
             continue
         command.process(guess)
Esempio n. 19
0
    def __init__(self):
        """ Configure command interface through Config class
		"""
        self.config_file = "c:/test-av/conf/vmware.conf"
        self.conf = Config(self.config_file)
        #
        # you can redefine the Command class providing vmrun full path:
        # self.cmd = Command("vmrun full path")
        #
        # TODO:
        #	- Command class with one argument
        self.cmd = Command(self.conf.path, self.conf.host, self.conf.user,
                           self.conf.passwd)

        # full paths of script neede for update
        self.cscriptPath = "c:/windows/system32/cscript.exe"
        self.netENScript = "c:/Users/avtest/Desktop/EnableIF.bat"
        self.netDISScript = "c:/Users/avtest/Desktop/DisableIF.bat"
        self.scriptPath = "c:/Users/avtest/Desktop/WUA_SearchDownloadInstall.vbs"
Esempio n. 20
0
def main():

    parser = ArgumentParser()

    parser.add_argument('-i',
                        '--interface',
                        help='interface to use',
                        dest='interface')
    parser.add_argument('-c',
                        '--control-interface',
                        help='path to control interface',
                        dest='ctrl',
                        default='/var/run/wpa_supplicant')

    args = parser.parse_args()

    wpa_sock = WPASock(args)

    cmd = Command(wpa_sock)
    cmd.cmdloop()
Esempio n. 21
0
 def connectAndListen(self, handler):
     """Set the transport handler, attach to the skype
     instance, and listen for input"""
     s = Skype4Py.Skype(Transport='x11')
     try:
         s.Attach()
     except:
         logger.error("Could not connect to skype!")
         logger.error("Verify that skype is launched and that the program is allowing us to connect")
         sys.exit(1)
     else:
         s.OnMessageStatus = handler
         try:
             while True:
                 time.sleep(1)
         except KeyboardInterrupt:
             c = Command(None)
             c.closeDB()
             logger.info("Terminating program...")
             sys.exit(0)
Esempio n. 22
0
def main():
    plugin_base = PluginBase(package="pycollect.plugins")
    plugin_source = plugin_base.make_plugin_source(searchpath=[PLUGIN_DIR])
    history = History()
    all_commands = dict()
    all_shortcuts = dict()

    # Load all plugins
    with plugin_source:
        for file in os.listdir(PLUGIN_DIR):
            if '.py' in file and '.pyc' not in file:
                mod = plugin_source.load_plugin(file.replace('.py', ''))
                cmd = mod.main_class()

                # Add the registered commands to the commands dict
                all_commands.update(cmd.commands)
                all_shortcuts.update(cmd.shortcuts)
    while True:
        text = get_input(u'> ',
                         history=history,
                         completer=WordCompleter(all_commands.keys()))

        cmd_name = text.split(' ')[0]
        command = None
        if cmd_name in all_commands:
            command = all_commands[cmd_name]
        elif cmd_name in all_shortcuts:
            command = all_shortcuts[cmd_name]
        else:
            Command.error("Command not found.")

        try:
            if command is not None:
                run(command(), text)
        except UsageException:
            command.help()
        except KeyboardInterrupt:
            pass
        except EOFError:
            sys.exit(0)
Esempio n. 23
0
	def __init__(self):
		""" Configure command interface through Config class
		"""
		self.config_file = "c:/test-av/conf/vmware.conf"
		self.conf = Config(self.config_file)
		#
		# you can redefine the Command class providing vmrun full path:
		# self.cmd = Command("vmrun full path")
		#
		# TODO:
		#	- Command class with one argument
		self.cmd = Command(self.conf.path, self.conf.host, self.conf.user, self.conf.passwd)
		
		# full paths of script neede for update
		self.netENScript="c:/Users/avtest/Desktop/EnableIF.bat"
		self.netDISScript="c:/Users/avtest/Desktop/DisableIF.bat"
		self.updScript="C:/Users/avtest/Desktop/AVUpdate.bat"
Esempio n. 24
0
File: bot.py Progetto: f0ur0ne/vicky
    def on_pubmsg(self, c, event):
        # TODO pull prefixes from config
        prefix = ";"
        msg = Message(message=event.arguments[0],
                      user=self.channel.getuser(event.source.nick))
        # TEMP stick in a module after events are wired
        #        if "http" in msg.message:
        #            try:
        #                urlexpression = "http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+"
        #                possible = re.findall(urlexpression, msg.message)
        #                req = get(possible[0])
        #                if req.status == 200:
        #                    soup = bs4(req.data, "html.parser")
        #                    if soup is not None:
        #                        try:
        #                            title = soup.title.string
        #                        except AttributeError as error:
        #                            pass
        #                        else:
        #                            self.sendmsg(title.strip())
        #            except:
        #                pass

        if msg.message.startswith(prefix):
            command = Command(prefix=prefix, data=msg)
            # TODO move these
            if command.name == "reload" or command.name == "load":
                if m := self.cm.import_module(command.message, self):
                    self.cm.add_cog(m, command.message, self)
                    self.sendmsg(f"{command.name}ed {command.message}")
                else:
                    self.sendmsg(f"failed to {command.name} {command.message}")
            elif command.name == "unload":
                if self.cm.unload(command.message):
                    self.sendmsg(f"unloaded {command.message}")
                else:
                    self.sendmsg(f"Could not unload {command.message}")
            elif command.name == "loaded":
                available = ", ".join(list(self.cm.modules.keys()))
                loaded = ", ".join(list(self.cm.cogs.keys()))

                self.sendmsg(f"Loaded: {loaded}")
                self.sendmsg(f"Available: {available}")
            else:
                self.cm.do_command(command)
Esempio n. 25
0
    async def consumer(self, message: str):
        tiny_crap = json.loads(message)
        if tiny_crap["tc"] == SE.PING:
            self.log.ping(tiny_crap)
            await self.pong()
        else:
            self.log.ws_event(message)
        if tiny_crap["tc"] == SE.NICK:
            self.accounts[tiny_crap["handle"]].nick = tiny_crap["nick"]
        if tiny_crap["tc"] == SE.CAPTCHA:
            self.log.warning(f"Captcha needed {tiny_crap}")
        if tiny_crap["tc"] == SE.USERLIST:
            for user in tiny_crap["users"]:
                self.accounts.update({user["handle"]: Account(**user)})
        if tiny_crap["tc"] == SE.JOINED:
            self.handle = tiny_crap["self"]["handle"]
        if tiny_crap["tc"] == SE.JOIN:
            self.accounts.update({tiny_crap["handle"]: Account(**tiny_crap)})
        if tiny_crap["tc"] == SE.QUIT:
            self.accounts.pop(tiny_crap["handle"])
        if tiny_crap["tc"] == SE.MSG:
            self.log.chat(f"{self.accounts[tiny_crap['handle']].username}: {tiny_crap['text']}")
            # check for a command, decorators are optional you can do it manually overriding msg in cog
            for prefix in self.settings["bot"]["prefixes"]:
                # if prefix match continue
                if tiny_crap["text"].startswith(prefix):
                    await self.attempt_command(
                        Command(prefix=prefix, data=tiny_crap, sender=self.handle_to_username(tiny_crap["handle"]),
                                account=self.accounts[tiny_crap["handle"]]))

        if tiny_crap["tc"] == SE.PASSWORD:
            await self.password()

        found = False
        # runs cog events
        if tiny_crap["tc"] in SE.ALL:
            found = True
            for cog in self.cogs:
                event = getattr(cog, tiny_crap["tc"])
                if not hasattr(event, "command"):
                    await event(tiny_crap)

        # check for unknown events
        if not found:
            self.log.debug(f"Unknown websocket event: {tiny_crap}")
Esempio n. 26
0
	def __init__(self):
		""" Configure command interface through Config class
		"""
		self.config_file = "c:/test-av/conf/vmware.conf"
		self.conf = Config(self.config_file)
		#
		# you can redefine the Command class providing vmrun full path:
		# self.cmd = Command("vmrun full path")
		#
		# TODO:
		#	- Command class with one argument
		self.cmd = Command(self.conf.path, self.conf.host, self.conf.user, self.conf.passwd)
		
		# full paths of script neede for update
		self.cscriptPath="c:/windows/system32/cscript.exe"
		self.netENScript="c:/Users/avtest/Desktop/EnableIF.bat"
		self.netDISScript="c:/Users/avtest/Desktop/DisableIF.bat"
		self.scriptPath="c:/Users/avtest/Desktop/WUA_SearchDownloadInstall.vbs"
Esempio n. 27
0
 def to_command(self, row):
     message = row[1]
     if len(message.split()) > 1:
         order = message.split()[0]
         arg = message.split(' ', 1)[1]
     else:
         order = row[1]
         arg = ''
     status = row[5]
     if status == 'COMPLETED':
         schedule = None
     else:
         schedule = row[3]
     c = Command(row[0],
                 order,
                 row[2],
                 row[4],
                 args=arg,
                 schedule=schedule,
                 result=row[6])
     return c
Esempio n. 28
0
class WinUpdate:
    def __init__(self):
        """ Configure command interface through Config class
		"""
        self.config_file = "c:/test-av/conf/vmware.conf"
        self.conf = Config(self.config_file)
        #
        # you can redefine the Command class providing vmrun full path:
        # self.cmd = Command("vmrun full path")
        #
        # TODO:
        #	- Command class with one argument
        self.cmd = Command(self.conf.path, self.conf.host, self.conf.user,
                           self.conf.passwd)

        # full paths of script neede for update
        self.cscriptPath = "c:/windows/system32/cscript.exe"
        self.netENScript = "c:/Users/avtest/Desktop/EnableIF.bat"
        self.netDISScript = "c:/Users/avtest/Desktop/DisableIF.bat"
        self.scriptPath = "c:/Users/avtest/Desktop/WUA_SearchDownloadInstall.vbs"

    def doUpdate(self, vmx):
        if vmx == 'all':
            #update all vms
            vms = self.conf.getMachines()

            sys.stdout.write("[*] Starting all guests.\n")
            for vm in vms:
                self.cmd.startup(self.conf.getVmx(vm))
                sleep(5)

            sys.stdout.write("[*] Enabling Networking on guests.\n")
            for vm in vms:
                self.cmd.executeCmd(self.conf.getVmx(vm), self.netENScript)

            sys.stdout.write("[*] Updating operatings system on guests.\n")
            for vm in vms:
                self.cmd.executeCmd(self.conf.getVmx(vm), self.cscriptPath,
                                    self.netDISScript)
            sys.stdout.write("[*] Done.\n")

        else:
            sys.stdout.write("[*] Starting %s.\n" % vmx)
            self.cmd.startup(self.conf.getVmx(vmx))
            sleep(60)
            sys.stdout.write("[*] Enabling Networking on %s.\n" % vmx)
            self.cmd.executeCmd(self.conf.getVmx(vmx), self.netENScript)
            sleep(10)
            sys.stdout.write("[*] Updating operatings system on %s.\n" % vmx)
            self.cmd.executeCmd(self.conf.getVmx(vmx), self.cscriptPath,
                                self.scriptPath)
            sys.stdout.write("[*] Done.\n")

    def doReboot(self, vmx):
        if vmx == "all":
            vms = self.conf.getMachines()
            sys.stdout.write("[*] Disabling network on guests.\n")
            for vm in vms:
                self.cmd.executeCmd(self.conf.getVmx(vm), self.netDISScript)
                sleep(5)
            sys.stdout.write("[*] Rebooting guests.\n")
            for vm in vms:
                self.cmd.reboot(self.conf.getVmx(vm))
                sleep(5)
        else:
            vm = self.conf.getVmx(vmx)
            sys.stdout.write("[*] Disabling network on %s.\n" % vmx)
            self.cmd.executeCmd(vm, self.netDISScript)
            sleep(20)
            sys.stdout.write("[*] Rebooting %s.\n" % vmx)
            self.cmd.reboot(vm)

    def refreshShot(self, vmx):
        if vmx == "all":
            sys.stdout.write("[*] Refresh snapshots on guests.\n")
            for vm in vms:
                self.cmd.refreshSnapshot(self.conf.getVmx(vm), 'current')
                sleep(30)
                self.cmd.suspend(self.conf.getVmx(vmx))
        else:
            sys.stdout.write("[*] Refresh snapshot of %s" % vmx)
            self.cmd.refreshSnapshot(self.conf.getVmx(vmx), 'current')
            self.cmd.suspend(self.conf.getVmx(vmx))
Esempio n. 29
0
class QuantumJumpBot:
    def __init__(self, settings):
        self._ws = None
        self.state = BotState(BotState.INITIALIZED)
        self.start_time = time.time()
        self.api = Http()
        self.cm = CogManager()
        self.settings = settings
        self.botconfig = self.settings.Bot
        self.ul: UserList
        self.room = self.botconfig.roomname

    async def wsend(self, data):
        if type(data) is list:
            data = "42{}".format(json.dumps(data))
        elif type(data) is str:
            type_exemptions = ["2probe", "5", "2"]
            if not data.startswith("42") and data not in type_exemptions:
                data = f"42{data}"
        else:
            print("invalid data type for wsend")
        await self._ws.send(data)
        print(f"SEND {data}")

    async def run(self):
        enabled_modules = self.settings.Modules["enabled"]
        self.cm.load_all(enabled_modules, bot=self)
        await self.connect()

    async def disconnect(self):
        self.state = BotState.DISCONNECT
        await self._ws.close()

    async def connect(self):
        await self.api.login(self.botconfig.username,
                             self.botconfig.password)

        async with websockets.connect(
                uri=await self.api.get_wss(),
                timeout=600,
                origin="https://jumpin.chat"
        ) as self._ws:
            print("Socket started")
            self.state = BotState.RUNNING
            await self.wsend("2probe")
            async for message in self._ws:
                await self._recv(message=message)

    async def _recv(self, message: str):
        print(f"RECV {message}")
        if message.isdigit():
            return
        if message == "3probe":
            await self.wsend("5")
            roommsg = [
                "room::join",
                {"room": self.botconfig.roomname}
            ]
            await self.wsend(roommsg)
            asyncio.create_task(self.pacemaker())
            return

        data = json.loads(message[2:])
        await self.cm.do_event(data=data)
        if data[0] == "self::join":
            nickmsg = [
                "room::handleChange", {
                    "userId": self.api.login_data.user.get("user_id"),
                    "handle": self.botconfig.nickname
                }
            ]
            await self.wsend(nickmsg)
            user_list_data = await self.api.getroominfo(room=str(self.room))

            self.ul = UserList(**user_list_data)
        if data[0] == "client::error":
            if error := data[1].get("error", False):
                # todo logger
                # todo create an enum for different error codes.

                if error == 'ERR_ACCOUNT_REQUIRED':
                    # if we do not disconnect, spy mode becomes possible.
                    await self.disconnect()
                    raise Exception("Account must be signed in to join this room.")
                if error == 'ENOSESSION':
                    # if we do not disconnect, spy mode becomes possible.
                    await self.disconnect()
                    raise Exception("Session was invalidated.")

        if data[0] == "room::message":
            prefix = self.botconfig.prefix
            if data[1].get("message").startswith(prefix):
                data[1].update({"sender": self.ul.get(handle=data[1].get("handle"))})
                c = Command(prefix=prefix, data=Message(**data[1]))
                if c.name == "reload" or c.name == "load":
                    if m := self.cm.import_module(c.message, self):
                        self.cm.add_cog(m, c.message, self)
                        await self.wsend(
                            Message.makeMsg(message=f"{c.name}ed {c.message}",
                                            room=self.room))
                    else:
                        await self.wsend(
                            Message.makeMsg(message=f"failed to {c.name} {c.message}",
                                            room=self.room))
                if c.name == "unload":
                    if self.cm.unload(c.message):
                        await self.wsend(
                            Message.makeMsg(message=f"unloaded {c.message}",
                                            room=self.room))
                    else:
                        await self.wsend(
                            Message.makeMsg(message=f"Could not unload {c.message}",
                                            room=self.room))
                if c.name == "loaded":
                    await self.wsend(
                        Message.makeMsg(message=f"modules: {self.cm.modules}, cogs:{self.cm.cogs}",
                                        room=self.room))
                await self.cm.do_command(c)
Esempio n. 30
0
    def task_destroy(self, task, config, guests):
        self.call(VagrantDestroyActor,
                  config=config,
                  sequence=False,
                  guests=guests)

    def task_up(self, task, config, guests, command_directory, sssd_directory,
                artifacts_directory):
        env = {
            'SSSD_TEST_SUITE_RSYNC':
            '{}:/shared/sssd'.format(sssd_directory),
            'SSSD_TEST_SUITE_SSHFS':
            '{}:/shared/artifacts {}:/shared/commands'.format(
                artifacts_directory, command_directory)
        }

        for guest in guests:
            self.vagrant(config, 'up', [guest], env=env, clear_env=True)

    def task_halt(self, task, config, guests):
        self.call(VagrantCommandActor('halt'),
                  config=config,
                  sequence=False,
                  guests=guests)


Commands = CommandList([
    Command('run', 'Run SSSD tests', RunTestsActor),
])
Esempio n. 31
0
from lib.command import Command
import sys

if __name__ == '__main__':
    argv = []
    kwarg = {}
    for a in sys.argv[1:]:
        if '=' in a:
            k, v = a.split('=')
            kwarg[k] = v
        else:
            argv.append(a)

    Command(*argv, **kwarg)()
Esempio n. 32
0
                if error == 'ENOSESSION':
                    await self.disconnect()
                    raise Exception("Session was invalidated.")

        if data[0] == "room::message":
            prefix = self.botconfig.prefix
            sender = self.ul.get_by_id(id=data[1].get("userId"))
            # bug when user is inside room twice
            # todo take a closer look at how the data invalidates.
            if sender:
                data[1].update({"sender": sender})

                self.log.chat(msg=f"{sender.handle}|{sender.username}: {data[1].get('message')}")

            if data[1].get("message").startswith(prefix):
                c = Command(prefix=prefix, data=Message(**data[1]))
                if c.name == "reload" or c.name == "load":
                    if m := self.cm.import_module(c.message, self):
                        self.cm.add_cog(m, c.message, self)
                        await self.wsend(
                            Message.makeMsg(message=f"{c.name}ed {c.message}",
                                            room=self.room))
                    else:
                        await self.wsend(
                            Message.makeMsg(message=f"failed to {c.name} {c.message}",
                                            room=self.room))
                elif c.name == "unload":
                    if self.cm.unload(c.message):
                        await self.wsend(
                            Message.makeMsg(message=f"unloaded {c.message}",
                                            room=self.room))
Esempio n. 33
0
                            default='all',
                            help='Guests that the client should enroll to. '
                            'Multiple guests can be set. (Default "all")')

        parser.epilog = textwrap.dedent('''
        This will renew the Windows evaluation license when it is expired. It
        will trigger guest reboot after the renewal.

        The renewal can be done only 6 times.
        ''')

    def run(self, args, argv):
        guests = args.guests if 'all' not in args.guests else ['all']
        self.ansible('rearm-windows-license.yml',
                     True,
                     limit=guests,
                     argv=argv)


Commands = Command(
    'provision', 'Provision machines',
    CommandParser([
        Command('host', 'Provision host machine', ProvisionHostActor),
        Command('guest', 'Provision selected guests machines',
                ProvisionGuestsActor),
        Command('enroll', 'Setup trusts and enroll client to domains',
                EnrollActor),
        Command('ldap', 'Import ldif into ldap server', LdapActor),
        Command('rearm', 'Renew windows license', RearmWindowsActor),
    ]))
Esempio n. 34
0
from docopt import docopt

from lib.client import TelnetClient
from lib.command import Command

if __name__ == '__main__':
    arguments = docopt(__doc__)
    log_conf_src = arguments['--log_conf']
    conf_src = arguments['--conf']
    outpath = arguments['--out']

    logging.config.fileConfig(fname=log_conf_src)

    cfg = configparser.ConfigParser()
    cfg.read(conf_src)

    username = cfg['USER']['name']
    password = cfg['USER']['password']
    board = cfg['CRAWL']['board']
    index = int(cfg['CRAWL']['index'])

    telnet_client = TelnetClient()
    telnet_client.start()
    ptt_cmd = Command(telnet_client)
    ptt_cmd.login(username, password)
    article = ptt_cmd.get_article(board, index)
    telnet_client.close()

    with open(outpath, 'a') as out_file:
        out_file.write(article)
Esempio n. 35
0
class WinUpdate:
	def __init__(self):
		""" Configure command interface through Config class
		"""
		self.config_file = "c:/test-av/conf/vmware.conf"
		self.conf = Config(self.config_file)
		#
		# you can redefine the Command class providing vmrun full path:
		# self.cmd = Command("vmrun full path")
		#
		# TODO:
		#	- Command class with one argument
		self.cmd = Command(self.conf.path, self.conf.host, self.conf.user, self.conf.passwd)
		
		# full paths of script neede for update
		self.cscriptPath="c:/windows/system32/cscript.exe"
		self.netENScript="c:/Users/avtest/Desktop/EnableIF.bat"
		self.netDISScript="c:/Users/avtest/Desktop/DisableIF.bat"
		self.scriptPath="c:/Users/avtest/Desktop/WUA_SearchDownloadInstall.vbs"
		

	def doUpdate(self, vmx):
		if vmx == 'all':
			#update all vms
			vms = self.conf.getMachines()
			
			sys.stdout.write("[*] Starting all guests.\n")
			for vm in vms:
				self.cmd.startup(self.conf.getVmx(vm))
				sleep(5)
				
			sys.stdout.write("[*] Enabling Networking on guests.\n")
			for vm in vms:
				self.cmd.executeCmd(self.conf.getVmx(vm), self.netENScript)

			sys.stdout.write("[*] Updating operatings system on guests.\n")
			for vm in vms:
				self.cmd.executeCmd(self.conf.getVmx(vm), self.cscriptPath, self.netDISScript)
			sys.stdout.write("[*] Done.\n")
					
		else:
			sys.stdout.write("[*] Starting %s.\n" % vmx)
			self.cmd.startup(self.conf.getVmx(vmx))
			sleep(60)
			sys.stdout.write("[*] Enabling Networking on %s.\n" % vmx)
			self.cmd.executeCmd(self.conf.getVmx(vmx), self.netENScript)
			sleep(10)
			sys.stdout.write("[*] Updating operatings system on %s.\n" % vmx)
			self.cmd.executeCmd(self.conf.getVmx(vmx), self.cscriptPath, self.scriptPath)
			sys.stdout.write("[*] Done.\n")
			
	
	def doReboot(self, vmx):
		if vmx == "all":
			vms = self.conf.getMachines()
			sys.stdout.write("[*] Disabling network on guests.\n")
			for vm in vms:
				self.cmd.executeCmd(self.conf.getVmx(vm), self.netDISScript)
				sleep(5)
			sys.stdout.write("[*] Rebooting guests.\n")
			for vm in vms:
				self.cmd.reboot(self.conf.getVmx(vm))
				sleep(5)	
		else:
			vm = self.conf.getVmx(vmx)
			sys.stdout.write("[*] Disabling network on %s.\n" % vmx)
			self.cmd.executeCmd(vm, self.netDISScript)
			sleep(20)
			sys.stdout.write("[*] Rebooting %s.\n" % vmx)
			self.cmd.reboot(vm)


	def refreshShot(self, vmx):
		if vmx == "all":
			sys.stdout.write("[*] Refresh snapshots on guests.\n")
			for vm in vms:
				self.cmd.refreshSnapshot(self.conf.getVmx(vm), 'current')
				sleep(30)
				self.cmd.suspend(self.conf.getVmx(vmx))
		else:
			sys.stdout.write("[*] Refresh snapshot of %s" % vmx)
			self.cmd.refreshSnapshot(self.conf.getVmx(vmx), 'current')
			self.cmd.suspend(self.conf.getVmx(vmx))
Esempio n. 36
0
        result = self.vagrant(args.config,
                              'box prune',
                              args=vgargs,
                              stdout=subprocess.PIPE)
        for (box, version) in regex.findall(result.stdout.decode('utf-8')):
            volume = '{box}_vagrant_box_image_{version}.img'.format(
                box=box.replace('/', '-VAGRANTSLASH-'), version=version)

            self.message('Box {}, version {} is outdated.'.format(
                box, version))
            self.message('  ...removing {}'.format(volume))

            self.shell('''
            sudo virsh vol-info {volume} --pool {pool} &> /dev/null
            if [ $? -ne 0 ]; then
                exit 0
            fi

            sudo virsh vol-delete {volume} --pool {pool}
            '''.format(volume=volume, pool='sssd-test-suite'))


Commands = Command(
    'box', 'Update and create boxes',
    CommandParser([
        Command('update', 'Update vagrant box',
                VagrantCommandActor('box update')),
        Command('prune', 'Delete all outdated vagrant boxes', PruneBoxActor),
        Command('create', 'Create new vagrant box', CreateBoxActor),
    ]))
Esempio n. 37
0
        return None


Commands = Command(
    'cloud', 'Access vagrant cloud',
    CommandParser([
        CommandGroup('Cloud Operations', [
            Command('list', 'List boxes stored in vagrant cloud',
                    CloudListActor),
            Command('upload', 'Upload boxes to vagrant cloud',
                    CloudUploadActor),
            Command('prune', 'Delete outdated versions of available boxes',
                    CloudPruneActor),
        ]),
        CommandGroup('Local Credentials', [
            Command('get-creds', 'Print your current credentials',
                    CloudGetCredentialsActor),
            Command('set-creds', 'Save your vagrant cloud token and username',
                    CloudSetCredentialsActor),
        ])
    ],
                  description=textwrap.dedent('''
These commands access vagrant cloud at https://app.vagrantup.com.

All commands takes --username and --token parameters that represents your
username and access token. You can use 'set-creds' command to save
these parameters in ./sssd-test-suite/vg-cloud.json. Please, keep in mind
that authentication token is stored in plain text.
''')))
Esempio n. 38
0
 def close(self):
     c = Command(None)
     c.closeDB()
 def __init__(self):
     Command.__init__(self, 'gringotts_checking')
     Builder.__init__(self, 'Assets:Checking:Gringotts', payee_accounts)
Esempio n. 40
0
class SyncServerBase(object):

    def __init__(self, logger, client_keys):
        self.logger = logger
        self.host_id = conf.HOST_ID
        self._rsync_popen = None
        self.is_running = False
        self.listen_ip = "0.0.0.0"
        self.inf_addr = (self.listen_ip, conf.INF_PORT)
        self.rsync_port = conf.RSYNC_PORT
        self.server = AES_RPC_Server(
            self.inf_addr,
            client_keys=client_keys,
            logger=logger,
            err_logger=logger,
        )

    def loop(self):
        self.server.loop()

    def start(self):
        if self.is_running:
            return
        self.is_running = True
        # self.start_rsync()
        self.server.start(20)

    def stop(self):
        if not self.is_running:
            return
        self.is_running = False
        self.server.stop()
        self.logger.info("server stopped")
        self.stop_rsync()

    def start_rsync(self):
        rsync_conf = """
uid=root
gid=root
use chroot=yes
og file=/dev/null
[%s]
    path=%s
    read only=no
    write only=yes
""" % (RSYNC_SERVER_NAME, conf.MOUNT_POINT_DIR)

        f = open(conf.RSYNC_CONF_PATH, "w")
        try:
            f.write(rsync_conf)
        finally:
            f.close()
        rsync_cmd = ["rsync", "--daemon", "--config=%s" %
                     (conf.RSYNC_CONF_PATH), "--no-detach"]
        rsync_cmd.append("--address=%s" % (self.listen_ip))
        rsync_cmd.append("--port=%s" % (self.rsync_port))
        #self._rsync_popen = subprocess.Popen(rsync_cmd, stderr=subprocess.PIPE, close_fds=True)
        self._rsync_popen = Command(rsync_cmd)
        self._rsync_popen.start()
        self.logger.info("started rsync, pid=%s" % (self._rsync_popen.pid))
        time.sleep(1)

    def stop_rsync(self):
        if self._rsync_popen is None:
            return
        self.logger.info("stopping rsync")
        try:
            os.kill(self._rsync_popen.pid, signal.SIGTERM)
            self._rsync_popen.wait()
        except OSError, e:
            if e[0] == errno.ESRCH:
                pass
            raise
        self.logger.info("rsync stopped")
Esempio n. 41
0
    def run(self, flags: FlagSet):
        super().run(flags)

        Command("cargo +nightly test").exec()