Exemplo n.º 1
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
Exemplo n.º 2
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)
Exemplo n.º 3
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
Exemplo n.º 4
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)
Exemplo n.º 5
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"
Exemplo n.º 6
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
Exemplo n.º 7
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()
Exemplo n.º 8
0
Arquivo: xen.py Projeto: 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)
Exemplo n.º 9
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
Exemplo n.º 10
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
Exemplo n.º 11
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
Exemplo n.º 12
0
Arquivo: bot.py Projeto: 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)
Exemplo n.º 13
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}")
Exemplo n.º 14
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"
Exemplo n.º 15
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"
Exemplo n.º 16
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()
Exemplo n.º 17
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
Exemplo n.º 18
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),
    ]))
Exemplo n.º 19
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),
])
Exemplo n.º 20
0
from lib.preference import Preference
from lib.voice import VoiceServer
from lib.command import Command
from pywinauto.application import Application

prg = Preference.getInstance().get_program()
app = Application().start(prg)
win = Preference.getInstance().get_window()
print(win)
cmd = Command(getattr(app, win))
server = VoiceServer()
server.listen(cmd)
Exemplo n.º 21
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)
Exemplo n.º 22
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))
Exemplo n.º 23
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)
Exemplo n.º 24
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),
    ]))
Exemplo n.º 25
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.
''')))
Exemplo n.º 26
0
    def run(self, flags: FlagSet):
        super().run(flags)

        Command("cargo +nightly test").exec()
Exemplo n.º 27
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)()