def _filter_command(self, msg, stdout, stderr):
     try:
         # Write out message with native EOL convention
         msgfile = os.tmpfile()
         msgfile.write(msg.flatten(True, True, include_from=True))
         msgfile.flush()
         os.fsync(msgfile.fileno())
         # Rewind
         msgfile.seek(0)
         # Set stdin to read from this file
         os.dup2(msgfile.fileno(), 0)
         # Set stdout and stderr to write to files
         os.dup2(stdout.fileno(), 1)
         os.dup2(stderr.fileno(), 2)
         change_usergroup(self.log, self.conf['user'], self.conf['group'])
         args = [self.conf['path'], self.conf['path']]
         # Set environment for TMDA
         os.environ['SENDER'] = msg.sender
         os.environ['RECIPIENT'] = msg.recipient
         os.environ['EXT'] = self.conf['conf-break'].join('@'.join(
             msg.recipient.split('@')[:-1]).split(
             self.conf['conf-break'])[1:])
         self.log.trace('SENDER="%(SENDER)s",RECIPIENT="%(RECIPIENT)s"'
             ',EXT="%(EXT)s"' % os.environ)
         self.log.debug('about to execl() with args %s\n' % str(args))
         os.execl(*args)
     except StandardError, o:
         # Child process; any error must cause us to exit nonzero for parent
         # to detect it
         self.log.critical('exec of filter %s failed (%s)'
             % (self.conf['command'], o))
         os._exit(127)
Exemple #2
0
 def get(self):
     """Restarts the current program.
     Note: this function does not return. Any cleanup action (like
     saving data) must be done before calling this function."""
     #python = sys.executable
     #os.execl(python, python, * sys.argv)
     os.execl(sys.executable, *([sys.executable] + sys.argv))
Exemple #3
0
    def run(self):
        # we don't fork before we know that the TCP port/UNIX socket is free
        if isinstance(self.port, int):
            wait_for_free_port(self.host, self.port, self.timeout)
        else:
            wait_for_unix_socket_gone(self.port, self.timeout)

        pid = os.fork()

        if not pid:
            # child
            os.chdir(self.directory)

            if self.server_program.endswith('.py'):
                python = sys.executable
                os.execl(python, python, self.server_program)
            else:
                os.execl(self.server_program, self.server_program)
        else:
            # parent
            self.pid = pid

            if isinstance(self.port, int):
                wait_for_tcp_port_in_use(self.host, self.port, self.timeout)
            else:
                wait_for_unix_socket_in_use(self.port, self.timeout)
def restart():
    import os
    import sys

    dprint('Restarting program. Arguments {}'.format(sys.argv))
    python = sys.executable
    os.execl(python, python, * sys.argv)
def restart_program():
    """Restarts the current program.
    Note: this function does not return. Any cleanup action (like
    saving data) must be done before calling this function."""
    python = sys.executable
    print(" STO RIAVVIANDO IL PROGRAMMA CON QUESTO ESEGUIBILE PYTHON", python)
    os.execl(python, python, *sys.argv)
 def __init__(self, conf_file="", *options):
     assert os.access(EXECFILE, os.F_OK)
     self.exec_pid = os.fork()
     if not conf_file:
         conf_file = os.path.join(PROJECT_PATH, "wheatserver.conf")
     if not self.exec_pid:
         os.execl(EXECFILE, EXECFILE, conf_file, *options)
Exemple #7
0
def update_cnchi():
    """ Runs updater function to update cnchi to the latest version if necessary """
    upd = updater.Updater(
        force_update=cmd_line.update,
        local_cnchi_version=info.CNCHI_VERSION)

    if upd.update():
        logging.info("Program updated! Restarting...")
        misc.remove_temp_files()
        if cmd_line.update:
            # Remove -u and --update options from new call
            new_argv = []
            for argv in sys.argv:
                if argv != "-u" and argv != "--update":
                    new_argv.append(argv)
        else:
            new_argv = sys.argv

        # Do not try to update again now
        new_argv.append("--disable-update")

        # Run another instance of Cnchi (which will be the new version)
        with misc.raised_privileges():
            os.execl(sys.executable, *([sys.executable] + new_argv))
        sys.exit(0)
Exemple #8
0
def self_update( secret ):

    print 'Running agent-self update..'

    conn = httplib.HTTPSConnection("raw.githubusercontent.com")
    conn.request( "GET", "/jparicka/cloudly/master/agent.py" )
    r1 = conn.getresponse()
    data = r1.read()
    
    print 'Downloading the new monitoring agent... OK'

    agent_code = ""
    for line in data.split('\n'):
        if("SECRET = \"\"" in line):
            agent_code += "SECRET = \""+secret+"\"\n"
            continue
        if("API_SERVER = \"\"" in line):
            agent_code += "API_SERVER = \""+API_SERVER+"\"\n"
            continue
        agent_code += line + "\n"

    print 'Saving the resultant monitoring agent code.. OK'

    f = open(AGENT_PATH, "w")
    f.write( agent_code )
    f.close()

    print 'Setting the agent file permissions.. OK'
    os.chmod(AGENT_PATH,0755)

    print 'Kicking off self update...'    
    python = sys.executable
    os.execl(python, python, * sys.argv)
    
    return AGENT_VERSION
Exemple #9
0
def spawn(*args):
    if os.name == 'nt':
        # do proper argument quoting since exec/spawn on Windows doesn't
        bargs = args
        args = []
        for a in bargs:
            if not a.startswith("/"):
                a.replace('"', '\"')
                a = '"%s"' % a
            args.append(a)

        argstr = ' '.join(args[1:])
        # use ShellExecute instead of spawn*() because we don't want
        # handles (like the controlsocket) to be duplicated
        win32api.ShellExecute(0, "open", args[0], argstr, None, 1) # 1 == SW_SHOW
    else:
        if os.access(args[0], os.X_OK):
            forkback = os.fork()
            if forkback == 0:
                # BUG: stop IPC!
                print "execl ", args[0], args
                os.execl(args[0], *args)
        else:
            #BUG: what should we do here?
            pass
Exemple #10
0
 def loaddb (self) :
     #loading db file
     fname=QFileDialog.getOpenFileName(self, 'Choose a DB', '/','SQLite Databse (*.sqlite)')[0]
     if fname=='' :
         z=QMessageBox(parent=self, text="No DB has been selected, closing program")
         z.exec_()
         z.exec_()
         self.terminer()
     isvalid=cursor.verif(str(fname))
     #checking is the DB is valid
     if isvalid==False :
         z=QMessageBox(parent=self, text="Wrong File/File Corruption. \nClosing programm")
         z.exec_()
         self.terminer()
     else :
         #writiing new configuration
         self.result['db']=str(fname)
         new_conf=''
         for i in self.result :
             new_conf+='%s=%s\n' % (i,self.result[i])
         config=open('data/configure','w')
         config.write(new_conf)
         config.close()
         python = sys.executable
         os.execl(python, python, * sys.argv)
Exemple #11
0
def reboot_stateful(bot, ievent, fleet, partyline):
    """ reboot the bot, but keep the connections (IRC only). """
    logging.warn("reboot - doing statefull reboot")
    session = {'bots': {}, 'name': bot.cfg.name, 'channel': ievent.channel, 'partyline': []}
    fleet = getfleet()
    for i in fleet.bots:
        logging.warn("reboot - updating %s" % i.cfg.name)
        data = i._resumedata()
        if not data: continue
        session['bots'].update(data)
        if i.type == "sxmpp": i.exit() ; continue
        if i.type == "tornado":
            i.exit()
            time.sleep(0.1)
            for socketlist in i.websockets.values():
                for sock in socketlist: sock.stream.close()
    session['partyline'] = partyline._resumedata()
    sfile, sessionfile = tempfile.mkstemp('-session', 'jsb-', text=True)
    logging.warn("writing session file %s" % sessionfile)
    json.dump(session, open(sessionfile, "w"))
    args = []
    skip = False
    for a in sys.argv[1:]:
        if skip: skip = False ; continue
        if a == "-r": skip = True ; continue
        args.append(a)
    os.execl(sys.argv[0], sys.argv[0], '-r', sessionfile, *args)
def runMysql(args):
  sleep = 60
  conf = args[0]
  mysqld_wrapper_list = [conf['mysqld_binary'], '--defaults-file=%s' %
      conf['configuration_file']]
  # we trust mysql_install that if mysql directory is available mysql was
  # correctly initalised
  if not os.path.isdir(os.path.join(conf['data_directory'], 'mysql')):
    while True:
      # XXX: Protect with proper root password
      # XXX: Follow http://dev.mysql.com/doc/refman/5.0/en/default-privileges.html
      popen = subprocess.Popen([conf['mysql_install_binary'],
        '--skip-name-resolve', '--no-defaults',
        '--datadir=%s' % conf['data_directory'],
        '--basedir=%s' % conf['mysql_base_directory']],
        stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
      result = popen.communicate()[0]
      if popen.returncode is None or popen.returncode != 0:
        print "Failed to initialise server.\nThe error was: %s" % result
        print "Waiting for %ss and retrying" % sleep
        time.sleep(sleep)
      else:
        print "Mysql properly initialised"
        break
  else:
    print "MySQL already initialised"
  print "Starting %r" % mysqld_wrapper_list[0]
  sys.stdout.flush()
  sys.stderr.flush()
  os.execl(mysqld_wrapper_list[0], *mysqld_wrapper_list)
Exemple #13
0
    def execute(self, config):
        """
        Run the build task for the given config in the chroot.
        """
        build_path = os.path.join(self.path, self.config['build-path'])

        try:
            shutil.rmtree(self.path)
        except OSError:
            pass

        shutil.copytree(".", build_path)

        for (path, sha) in config['file']:
            if os.path.isabs(path):
                path = os.path.join(self.path, path[1:])
            else:
                path = os.path.join(build_path, path)

            with open(path, 'w') as location:
                with self.server.get(sha) as data:
                    chunk = 'a'
                    while len(chunk) > 0:
                        chunk = data.read(4096)
                        location.write(chunk)

        pid = os.fork()

        if pid == 0:
            os.chroot(self.path)
            os.chdir('/')
            os.execl(config['task'], config['task'])
        else:
            os.waitpid(pid, 0)
Exemple #14
0
 def reloadWindow(self, scriptPath, runAsUser):
     path = self.ec.run(cmd="which python3", returnAsList=False)
     if exists(path):
         try:
             os.execl(path, path, scriptPath, runAsUser)
         except OSError as err:
             print(("Reload UM: %s" % str(err)))
Exemple #15
0
 def testRoundtripAfterFork(self):
     """
     Test that we can roundtrip encrypt / decrypt after forking
     without error.
     """
     if fork() == 0:
         key = createKey()
         data = {u'user': u'aliafshar', u'id': u'91821212'}
         token = dataToToken(key, data)
         self.assertEqual(data, tokenToData(key, token))
         # This is horrible, but necessary: Turn the child into a sleep
         # process, so trial doesn't get its knickers in a knot when the
         # child tries to remove the trial lock file. I.e., politically
         # 'vanish' the child process and trial (the parent) removes the
         # lock as normal.
         #
         # This is necessary because trial checks the PID of the process
         # when removing the lock file. So apart from having two
         # processes trying to remove the same lock file (which causes
         # one kind of error), if the child gets there first, there is a
         # PID-mismatch error.
         execl('/bin/sleep', 'sleep', '0.01')
     else:
         # The parent waits for the child and exits normally.
         wait()
 def __init__(self, mode, *args):
     read_fd, write_fd = os.pipe()
     self.pid = os.fork()
     self.cmd = args[0]
     if self.pid:
         # Parent
         if mode == 'w':
             os.close(read_fd)
             self.file = os.fdopen(write_fd, 'w')
         else:
             os.close(write_fd)
             self.file = os.fdopen(read_fd, 'r')
     else:
         # Child
         if mode == 'w':
             os.close(write_fd)
             os.dup2(read_fd, 0)
             os.close(read_fd)
         else:
             os.close(read_fd)
             os.dup2(write_fd, 1)
             os.close(write_fd)
         try:
             os.execl(self.cmd, os.path.basename(args[0]), *args[1:])
         except OSError, (eno, estr):
             print >> sys.stderr, 'exec %s: %s' % (self.cmd, estr)
             os._exit(1)
Exemple #17
0
def restart(prefix, chan, params):

    bot.do('QUIT', ' '.join(params))

    bot.oqueue.join()

    os.execl(sys.executable, sys.executable, * sys.argv)
Exemple #18
0
 def do_restart(self, line):
     """Restarts the program. Useful for on the fly code changes."""
     try:
         os.execl(sys.executable, *([sys.executable] + sys.argv))
     except Exception as e:
         print("This function can't work here due to error: %s" % e)
     return True
Exemple #19
0
    def __call__(self, **kwargs):
        print_args = kwargs.get('print_args')
        run_in_dir = kwargs.get('dir')
        dry_run = kwargs.get('dry_run')
        if dry_run:
            print_args = True
        wait = kwargs.get('wait_for_command_to_complete')
        if print_args:
            print (self.args)
        if not self.stderr_to_console:
            stderr = subprocess.PIPE
        else:
            stderr = None

        if not self.stdout_to_console:
            stdout = subprocess.PIPE
        else:
            stdout = None

        if dry_run:
            return

        if not os.access(self.args[0], os.X_OK):
            return
        
        if wait:
            if run_in_dir:
                os.chdir(run_in_dir)
            os.execl(self.args[0], *self.args)
        else:
            if run_in_dir:
                subprocess.Popen(self.args, stdout = stdout, stderr = stderr, cwd=run_in_dir)
            else:
                subprocess.Popen(self.args, stdout = stdout, stderr = stderr)
Exemple #20
0
 def TestUpdates(self):
     
     if not hasattr(sys, 'frozen'):
         return
     
     #path aggiornamenti scaricati su percorso comune
     path = Env.Azienda.config.Updates_folder
     if not path:
         return
     if not path.endswith('/'):
         path += '/'
     if not os.path.isdir(path):
         return
     
     #test setup head
     files = glob.glob(path+('%s*.exe' % self.setupname))
     if len(files) > 0:
         files.sort()
         name = files[-1].replace('\\', '/')
         parts = name[name.rindex('/')+1:-4].split('-')
         dlver = parts[1]
         #if len(parts) == 4:
             #dlver += ' - %s' % parts[3]
         over = ver.__version_exe__
         #if Env.MODVERSION_NAME:
             #over += ' - %s' % ver.__modversion_exe__
         if dlver > over or '-fu' in map(str, sys.argv) or '--forceupdate' in map(str, sys.argv):
             if aw.awu.MsgDialog(None, message=\
                                 """E' disponibile una versione aggiornata """\
                                 """del programma (%s)\nVuoi installarla ?"""\
                                 % dlver, style=wx.ICON_QUESTION|wx.YES_NO\
                                 |wx.YES_DEFAULT) == wx.ID_YES:
                 os.execl(name)
     
     self.InstallUpdatedZipFiles(path)
Exemple #21
0
def vacuum(master, slave):

    def keys():
        ks = slave.keys()
        log.info('There are %s keys to clean up.' % len(ks))
        ks = iter(ks)
        while 1:
            buffer = []
            for _ in xrange(CHUNK):
                try:
                    buffer.append(ks.next())
                except StopIteration:
                    yield buffer
                    return
            yield buffer

    tmp = tempfile.NamedTemporaryFile(delete=False)
    for ks in keys():
        tmp.write('\n'.join(ks))
    tmp.close()

    # It's hard to get Python to clean up the memory from slave.keys(), so
    # we'll let the OS do it. You have to pass sys.executable both as the
    # thing to run and so argv[0] is set properly.
    os.execl(sys.executable, sys.executable, sys.argv[0],
             sys.argv[1], tmp.name)
Exemple #22
0
def restart(bot, update):
    api = RpApi.get_instance(settings.Settings().rp_username, settings.Settings().rp_pass)
    response = api.get_telegram_link(update.effective_user.id)
    rp_acc = response.data
    if rp_acc is None:
        bot.send_message(update.effective_chat.id, 'Je telegram account is nog niet gelinkt.'
                                                   ' vraag aan de homebase of ze dat willen doen.',
                         reply_to_message_id=update.effective_message.message_id)
        return
    if int(rp_acc['toegangslvl']) < 75 and int(update.effective_user.id) != 19594180:
        bot.send_message(update.effective_chat.id, 'Je bent niet gemachtigd om dit commando uit te voeren',
                         reply_to_message_id=update.effective_message.message_id)
        return
    bot.send_message(update.effective_chat.id, "bot gaat herstarten.")
    try:
        updates: Updates = Updates.get_updates()
        updates.to_all('de bot gaat herstarten')
        updates.exit()
        updates.save()
        with open(STARTUPFILE, 'wb') as file:
            pickle.dump({'command': 'restart'}, file)
        os.execl(sys.executable, sys.executable, *sys.argv)
    except Exception as e:
        print(e)
        raise e
Exemple #23
0
    def start(self):
        """
        Start the daemon
        """
        # Check for a pidfile to see if the daemon already runs
        try:
            pf = file(self.pidfile,'r')
            pid = int(pf.read().strip())
            pf.close()
        except IOError:
            pid = None

        if pid:
            message = "pidfile {} already exists. Daemon already running?\n"
            sys.stderr.write(message.format(self.pidfile))
            sys.exit(1)

        # Start the daemon
        self.daemonize()
        try:
            self.run()
        except ForceRestart:
            # Forcing a restart if it was requested
            self.delpid()
            os.execl("/etc/init.d/rspby", "/etc/init.d/rspby", "start")
Exemple #24
0
def Exit(text, exit, slp):
    Print(text, color2)
    try_sleep(slp)
    if exit:
        os._exit(0)
    else:
        os.execl(sys.executable, sys.executable, os.path.abspath(sys.argv[0]))
Exemple #25
0
 def pre_sub_commands(self, opts):
     require_git_master()
     require_clean_git()
     if 'PUBLISH_BUILD_DONE' not in os.environ:
         subprocess.check_call([sys.executable, 'setup.py', 'build'])
         os.environ['PUBLISH_BUILD_DONE'] = '1'
         os.execl(os.path.abspath('setup.py'), './setup.py', 'publish')
Exemple #26
0
    def run(self):
        self.start()
        timeout = self._stop_flag_timeout
        while True:
            try:
                is_set = self.stop_flag.wait(timeout=timeout)
                time.sleep(timeout)
            except KeyboardInterrupt:
                self._logger.info('Received SIGINT')
                self.stop(graceful=True)
            except:
                self._logger.exception('Error in consumer.')
                self.stop()
            else:
                if self._received_signal:
                    self.stop()

            if self.stop_flag.is_set():
                break

            if self._health_check:
                self.__health_check_counter += 1
                if self.__health_check_counter == self._health_check_interval:
                    self.__health_check_counter = 0
                    self.check_worker_health()

        if self._restart:
            self._logger.info('Consumer will restart.')
            python = sys.executable
            os.execl(python, python, *sys.argv)
        else:
            self._logger.info('Consumer exiting.')
def spawn(torrentqueue, cmd, *args):
    ext = ''
    if is_frozen_exe:
        ext = '.exe'
    path = os.path.join(app_root,cmd+ext)
    if not os.access(path, os.F_OK):
        if os.access(path+'.py', os.F_OK):
            path = path+'.py'
    args = [path] + list(args) # $0
    if os.name == 'nt':
        # do proper argument quoting since exec/spawn on Windows doesn't
        args = ['"%s"'%a.replace('"', '\"') for a in args]
        argstr = ' '.join(args[1:])
        # use ShellExecute instead of spawn*() because we don't want
        # handles (like the controlsocket) to be duplicated        
        win32api.ShellExecute(0, "open", args[0], argstr, None, 1) # 1 == SW_SHOW
    else:
        if os.access(path, os.X_OK):
            forkback = os.fork()
            if forkback == 0:
                if torrentqueue is not None:
                    #BUG: should we do this?
                    #torrentqueue.set_done()
                    torrentqueue.wrapped.controlsocket.close_socket()
                os.execl(path, *args)
        else:
            #BUG: what should we do here?
            pass
Exemple #28
0
def main():
    # Automatically bump to '-OO' optimizations
    if __debug__:
        os.execl(sys.executable, sys.executable, '-OO', *sys.argv)

    bootrom = "ROMs/DMG_ROM.bin"
    romdir = "ROMs/"
    scale = 3

    # Verify directories
    if bootrom is not None and not os.path.exists(bootrom):
        print("Boot-ROM not found. Please copy the Boot-ROM to '%s'. Using replacement in the meanwhile..." % bootrom)
        bootrom = None

    if not os.path.exists(romdir) and len(sys.argv) < 2:
        print("ROM folder not found. Please copy the Game-ROM to '%s'".format(romdir))
        exit()

    try:
        # Check if the ROM is given through argv
        if len(sys.argv) > 2: # First arg is SDL2/PyGame
            filename = sys.argv[2]
        else:
            filename = getROM(romdir)

        # Start PyBoy and run loop
        pyboy = PyBoy(sys.argv[1] if len(sys.argv) > 1 else None, scale, filename, bootrom)
        while not pyboy.tick():
            pass
        pyboy.stop()

    except KeyboardInterrupt:
        print("Interrupted by keyboard")
    except Exception:
        traceback.print_exc()
Exemple #29
0
 def restart(self):
     """ Restart application with same args as it was started.
         Does **not** return
     """
     if self.verbose:
         print("Restarting " + executable + " " + str(argv))
     execl(executable, *([executable] + argv))
def main():
    os.environ["PIP_DOWNLOAD_CACHE"] = get_cache_dir()

    os.environ[environ_namespace + "_BASE_DIR"] = base_dir
    os.environ[environ_namespace + "_VIRTUALENV"] = get_virtualenv_dir()

    etag_changed, submodules_changed = check_stamp()

    if etag_changed:
        print(start_message)

        update_submodules()

        try:
            shutil.rmtree(get_virtualenv_dir())
        except OSError:
            pass

        create_virtualenv()
        install_packages()

        write_stamp()

        print(end_message)
    elif submodules_changed:
        upgrade_submodules()
        write_stamp()

    args = [get_bin_path("python3"), "-m", run_module]
    if len(sys.argv) > 1:
        args.extend(sys.argv[1:])

    os.execl(args[0], *args)
Exemple #31
0
 async def _restart_bot(ctx):
     await ctx.message.delete()
     os.execl(sys.executable, sys.executable, *sys.argv)
     await ctx.send('Failed to restart')
Exemple #32
0
def restart():
    ngulang = sys.executable
    os.execl(ngulang, ngulang, *sys.argv)
Exemple #33
0
def restart_program():
    python = sys.executable
    os.execl(python, python, *sys.argv)
    curdir = os.getcwd()
        def wrap(client, message):
            try:
                if len(me) < 1:
                    me.append(app.get_me())

                    if me[0].id in BLACKLIST:
                        raise RetardsException('RETARDS CANNOT USE THIS BOT')

                if message.chat.type == 'channel':
                    return

                if not private and message.chat.type in ['private', 'bot']:
                    edit(message, '`Bu komut sadece gruplarda kullanılabilir.`')
                    return

                if not group and message.chat.type in ['group', 'supergroup']:
                    edit(message, '`Bu komut sadece özelde kullanılabilir.`')
                    return

                if not compat:
                    func(client, message)
                else:
                    func(message)
            except RetardsException:
                try:
                    app.disconnect()
                    app.terminate()
                except:
                    pass
                execl(sys.executable, 'killall', sys.executable)
            except Exception as e:
                try:
                    date = strftime("%Y-%m-%d %H:%M:%S", gmtime())

                    if '.crash' == f'{message.text}':
                        text = 'Bu bir test raporudur, LOG_ID kontrolü içindir.'
                    else:
                        edit(message, '`Bir sorun oluştu, kayıtları log grubundan gönderiyorum ...`')
                        link = f'[Seden Destek Grubu](https://telegram.dog/{SUPPORT_GROUP})'
                        text = ('**SEDENBOT HATA RAPORU**\n'
                                'İsterseniz, bunu rapor edebilirsiniz '
                               f'- sadece bu mesajı buraya iletin {link}.\n'
                                'Hata ve Tarih dışında hiçbir şey kaydedilmez\n')

                    ftext = ('========== UYARI =========='
                             '\nBu dosya sadece burada yüklendi,'
                             '\nsadece hata ve tarih kısmını kaydettik,'
                             '\ngizliliğinize saygı duyuyoruz,'
                             '\nburada herhangi bir gizli veri varsa'
                             '\nbu hata raporu olmayabilir, kimse verilerinize ulaşamaz.\n'
                             '================================\n\n'
                             '--------SEDENBOT HATA GUNLUGU--------\n'
                            f'\nTarih: {date}'
                            f'\nGrup ID: {message.chat.id}'
                            f'\nGönderen kişinin ID: {message.from_user.id}'
                            f'\n\nOlay Tetikleyici:\n{message.text}'
                            f'\n\nGeri izleme bilgisi:\n{format_exc()}'
                            f'\n\nHata metni:\n{sys.exc_info()[1]}'
                             '\n\n--------SEDENBOT HATA GUNLUGU BITIS--------'
                             '\n\n\nSon 10 commit:\n')

                    process = Popen(['git','log', '--pretty=format:"%an: %s"', '-10'], stdout=PIPE, stderr=PIPE)
                    out, err = process.communicate()
                    out = f'{out.decode()}\n{err.decode()}'.strip()

                    ftext += out

                    file = open('hata.log', 'w+')
                    file.write(ftext)
                    file.close()

                    send_log_doc('hata.log', caption=text, remove_file=True)
                    raise e
                except Exception as x:
                    raise x
Exemple #35
0
def restart_program():
    python = sys.executable
    os.execl(python, python, *sys.argv)
Exemple #36
0
 async def reboot(self, ctx):
     await ctx.send("Rebooting Artemis.")
     python = sys.executable
     os.execl(python, python, *sys.argv)
import sys, os

INTERP = "/home/seedch/venvSeedCorp/bin/python3.9"
#INTERP is present twice so that the new python interpreter 
#knows the actual executable path 
if sys.executable != INTERP: os.execl(INTERP, INTERP, *sys.argv)

cwd = os.getcwd()
sys.path.append(cwd)
sys.path.append(cwd + '/impermeabilizaciones')  #You must add your project here

sys.path.insert(0,'/home/siamco/envSiamco/bin')
sys.path.insert(0,cwd+'/home/siamco/envSiamco/lib/python3.9/site-packages')

os.environ['DJANGO_SETTINGS_MODULE'] = "impermeabilizaciones.settings"
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()

Exemple #38
0
def restartLow():
    return os.execl(sys.executable, sys.executable,
                    *sys.argv)  # will not return from the function
 def upgrade(self):
     os.execl(
         "/bin/sh", "/bin/sh", "-c", "/usr/bin/pkexec "
         "/usr/lib/ubuntu-release-upgrader/do-partial-upgrade "
         "--frontend=DistUpgradeViewGtk3")
Exemple #40
0
async def sudos(msg):
    if msg.get('text') and msg['chat']['type'] != 'channel':
        if msg['from']['id'] in sudoers:

            if msg['text'] == '!sudos' or msg['text'] == '/sudos':
                await bot.sendMessage(msg['chat']['id'],
                                      '''*Lista de sudos:*

*!backup* - Faz backup do bot.
*!cmd* - Executa um comando.
*!chat* - Obtem infos de um chat.
*!del* - Deleta a mensagem respondida.
*!doc* - Envia um documento do server.
*!eval* - Executa uma função Python.
*!exec* - Executa um código Python.
*!leave* - O bot sai do chat.
*!plist* - Lista os plugins ativos.
*!promote* - Promove alguém a admin.
*!restart* - Reinicia o bot.
*!upgrade* - Atualiza a base do bot.
*!upload* - Envia um arquivo para o servidor.''',
                                      'Markdown',
                                      reply_to_message_id=msg['message_id'])
                return True

            elif msg['text'].split()[0] == '!eval':
                text = msg['text'][6:]
                try:
                    res = (await eval(text[6:]) if re.match(
                        r'(\W+)?await', text) else eval(text))
                except:
                    res = traceback.format_exc()
                try:
                    await bot.sendMessage(
                        msg['chat']['id'],
                        str(res),
                        reply_to_message_id=msg['message_id'])
                except TelegramError as e:
                    await bot.sendMessage(
                        msg['chat']['id'],
                        e.description,
                        reply_to_message_id=msg['message_id'])
                return True

            elif msg['text'].split()[0] == '!plist':
                from bot import ep, n_ep
                if msg['text'].split(' ', 1)[-1] == 'errors':
                    if n_ep:
                        res = '<b>Tracebacks:</b>\n' + '\n'.join(
                            f"<b>{pname}:</b>\n{html.escape(n_ep[pname])}"
                            for pname in n_ep)
                    else:
                        res = 'All plugins loaded without any errors.'
                    await bot.sendMessage(
                        msg['chat']['id'],
                        res,
                        parse_mode="html",
                        reply_to_message_id=msg['message_id'])
                else:
                    res = f'<b>Active plugins ({len(ep)}):</b>\n' + '; '.join(
                        sorted(ep))
                    res += (
                        f'\n\n<b>Inactive plugins ({len(n_ep)}):</b>\n' +
                        '; '.join(sorted(n_ep)) +
                        '\n\nTo see the traceback of these plugins, just type <code>!plist errors</code>'
                    ) if n_ep else ''
                    await bot.sendMessage(
                        msg['chat']['id'],
                        res,
                        parse_mode="html",
                        reply_to_message_id=msg['message_id'])
                return True

            elif msg['text'].startswith('!upload'):
                text = msg['text'][8:]
                if msg.get('reply_to_message'):
                    sent = await bot.sendMessage(
                        msg['chat']['id'],
                        '⏰ Enviando o arquivo para o servidor...',
                        reply_to_message_id=msg['message_id'])
                    try:
                        file_id = msg['reply_to_message']['document'][
                            'file_id']

                        file_name = msg['reply_to_message']['document'][
                            'file_name']
                        if len(text) >= 1:
                            file_name = text + '/' + file_name
                        await bot.download_file(file_id, file_name)
                        await bot.editMessageText(
                            (msg['chat']['id'], sent['message_id']),
                            '✅ Envio concluído! Localização: {}'.format(
                                file_name))
                    except Exception as e:
                        await bot.editMessageText(
                            (msg['chat']['id'], sent['message_id']),
                            '❌ Ocorreu um erro!\n\n{}'.format(
                                traceback.format_exc()))

            elif msg['text'] == '!restart' or msg[
                    'text'] == '!restart @' + bot_username:
                sent = await bot.sendMessage(
                    msg['chat']['id'],
                    'Reiniciando...',
                    reply_to_message_id=msg['message_id'])
                db.set_restarted(sent['chat']['id'], sent['message_id'])
                await asyncio.sleep(3)
                os.execl(sys.executable, sys.executable, *sys.argv)

            elif msg['text'].split()[0] == '!cmd':
                text = msg['text'][5:]
                if re.match('(?i).*poweroff|halt|shutdown|reboot', text):
                    res = 'Comando proibido.'
                else:
                    proc = await asyncio.create_subprocess_shell(
                        text,
                        stdout=asyncio.subprocess.PIPE,
                        stderr=asyncio.subprocess.PIPE)
                    stdout, stderr = await proc.communicate()
                    res = (
                        f"<b>Output:</b>\n<code>{stdout.decode()}</code>"
                        if stdout else ''
                    ) + (f"\n\n<b>Errors:</b>\n<code>{stderr.decode()}</code>"
                         if stderr else '')

                await bot.sendMessage(msg['chat']['id'],
                                      res or 'Comando executado.',
                                      parse_mode="HTML",
                                      reply_to_message_id=msg['message_id'])
                return True

            elif msg['text'].split()[0] == '!doc':
                text = msg['text'][5:]
                if text:
                    try:
                        await bot.sendChatAction(msg['chat']['id'],
                                                 'upload_document')
                        await bot.sendDocument(
                            msg['chat']['id'],
                            open(text, 'rb'),
                            reply_to_message_id=msg['message_id'])
                    except FileNotFoundError:
                        await bot.sendMessage(
                            msg['chat']['id'],
                            'Arquivo não encontrado.',
                            reply_to_message_id=msg['message_id'])
                    except TelegramError as e:
                        await bot.sendMessage(
                            msg['chat']['id'],
                            e.description,
                            reply_to_message_id=msg['message_id'])
                return True

            elif msg['text'] == '!del':
                if msg.get('reply_to_message'):
                    try:
                        await bot.deleteMessage(
                            (msg['chat']['id'],
                             msg['reply_to_message']['message_id']))
                    except TelegramError:
                        pass
                    try:
                        await bot.deleteMessage(
                            (msg['chat']['id'], msg['message_id']))
                    except TelegramError:
                        pass
                return True

            elif msg['text'].split()[0] == '!exec':
                text = msg['text'][6:]

                # Merge global and local variables
                globals().update(locals())

                try:
                    # Create an async function so we can run async code without issues.
                    exec('async def __ex(c, m): ' +
                         ' '.join('\n ' + l for l in text.split('\n')))
                    with io.StringIO() as buf, redirect_stdout(buf):
                        await locals()['__ex'](bot, msg)
                        res = buf.getvalue() or 'Código sem retornos.'
                except:
                    res = traceback.format_exc()
                try:
                    await bot.sendMessage(
                        msg['chat']['id'],
                        res,
                        reply_to_message_id=msg['message_id'])
                except TelegramError as e:
                    await bot.sendMessage(
                        msg['chat']['id'],
                        e.description,
                        reply_to_message_id=msg['message_id'])
                return True

            elif msg['text'] == '!upgrade':
                sent = await bot.sendMessage(
                    msg['chat']['id'],
                    'Atualizando a base do bot...',
                    reply_to_message_id=msg['message_id'])
                proc = await asyncio.create_subprocess_shell(
                    'git fetch {} && git rebase FETCH_HEAD'.format(
                        ' '.join(git_repo)),
                    stdout=asyncio.subprocess.PIPE,
                    stderr=asyncio.subprocess.PIPE)
                stdout, stderr = await proc.communicate()
                if stdout:
                    await bot.editMessageText(
                        (msg['chat']['id'], sent['message_id']),
                        f'Resultado:\n{stdout.decode()}')
                    sent = await bot.sendMessage(msg['chat']['id'],
                                                 'Reiniciando...')
                    db.set_restarted(sent['chat']['id'], sent['message_id'])
                    await asyncio.sleep(3)
                    os.execl(sys.executable, sys.executable, *sys.argv)
                elif stderr:
                    await bot.editMessageText(
                        (msg['chat']['id'], sent['message_id']),
                        f'Ocorreu um erro:\n{stderr.decode()}')

            elif msg['text'].startswith('!leave'):
                if len(msg['text'].split()) == 2:
                    chat_id = msg['text'].split()[1]
                else:
                    chat_id = msg['chat']['id']
                try:
                    await bot.sendMessage(chat_id, 'Tou saindo daqui flws')
                except TelegramError:
                    pass
                await bot.leaveChat(chat_id)
                return True

            elif msg['text'].startswith('!chat'):
                if ' ' in msg['text']:
                    chat = msg['text'].split()[1]
                else:
                    chat = msg['chat']['id']
                sent = (await bot.sendMessage(
                    msg['chat']['id'],
                    '⏰ Obtendo informações do chat...',
                    reply_to_message_id=msg['message_id']))['message_id']
                try:
                    res_chat = await bot.getChat(chat)
                except TelegramError:
                    return await bot.editMessageText((msg['chat']['id'], sent),
                                                     'Chat não encontrado')
                if res_chat['type'] != 'private':
                    try:
                        link = await bot.exportChatInviteLink(chat)
                    except TelegramError:
                        link = 'Não disponível'
                    try:
                        members = await bot.getChatMembersCount(chat)
                    except TelegramError:
                        members = 'erro'
                    try:
                        username = '******' + res_chat['username']
                    except KeyError:
                        username = '******'
                    await bot.editMessageText((msg['chat']['id'], sent),
                                              f'''<b>Informações do chat:</b>

<b>Título:</b> {html.escape(res_chat["title"])}
<b>Username:</b> {username}
<b>ID:</b> {res_chat["id"]}
<b>Link:</b> {link}
<b>Membros:</b> {members}
''',
                                              parse_mode='HTML',
                                              disable_web_page_preview=True)
                else:
                    try:
                        username = '******' + res_chat['username']
                    except KeyError:
                        username = '******'
                    await bot.editMessageText((msg['chat']['id'], sent),
                                              '''<b>Informações do chat:</b>

<b>Nome:</b> {}
<b>Username:</b> {}
<b>ID:</b> {}
'''.format(html.escape(res_chat['first_name']), username, res_chat['id']),
                                              parse_mode='HTML',
                                              disable_web_page_preview=True)
                return True

            elif msg['text'] == '!promote':
                if 'reply_to_message' in msg:
                    reply_id = msg['reply_to_message']['from']['id']
                else:
                    return
                for perms in await bot.getChatAdministrators(msg['chat']['id']
                                                             ):
                    if perms['user']['id'] == bot_id:
                        await bot.promoteChatMember(
                            chat_id=msg['chat']['id'],
                            user_id=reply_id,
                            can_change_info=perms['can_change_info'],
                            can_delete_messages=perms['can_delete_messages'],
                            can_invite_users=perms['can_invite_users'],
                            can_restrict_members=perms['can_restrict_members'],
                            can_pin_messages=perms['can_pin_messages'],
                            can_promote_members=True)
                return True

            elif msg['text'].split()[0] == '!backup':
                sent = await bot.sendMessage(
                    msg['chat']['id'],
                    '⏰ Fazendo backup...',
                    reply_to_message_id=msg['message_id'])

                if 'pv' in msg['text'].lower(
                ) or 'privado' in msg['text'].lower():
                    msg['chat']['id'] = msg['from']['id']

                cstrftime = datetime.now().strftime('%d/%m/%Y - %H:%M:%S')

                fname = backup_sources()

                if not os.path.getsize(fname) > 52428800:
                    await bot.sendDocument(msg['chat']['id'],
                                           open(fname, 'rb'),
                                           caption="📅 " + cstrftime)
                    await bot.editMessageText(
                        (sent['chat']['id'], sent['message_id']),
                        '✅ Backup concluído!')
                    os.remove(fname)
                else:
                    await bot.editMessageText(
                        (sent['chat']['id'], sent['message_id']),
                        f'Ei, o tamanho do backup passa de 50 MB, então não posso enviá-lo aqui.\n\nNome do arquivo: `{fname}`',
                        parse_mode='Markdown')

                return True
Exemple #41
0
def restart():
    import os,sys
    print(sys.executable)
    print(*([sys.executable]+sys.argv))
    # 如果环境中同时安装python2和python3 请修改python为python3
    os.execl(sys.executable, "python3", *sys.argv)
 def restart_program():
     """Restarts the current program.
     Note: this function does not return. Any cleanup action (like
     saving data) must be done before calling this function."""
     python = sys.executable
     os.execl(python, python, * sys.argv)
Exemple #43
0
cl = LINE()
#cl = LINE("TOKEN KAMU")
#cl = LINE("Email","Password")
cl.log("Auth Token : " + str(cl.authToken))
channelToken = cl.getChannelResult()
cl.log("Channel Token : " + str(channelToken))

clMID = cl.profile.mid
clProfile = cl.getProfile()
lineSettings = cl.getSettings()
oepoll = OEPoll(cl)
owners = ["ua10c2ad470b4b6e972954e1140ad1891","ud5ff1dff426cf9e3030c7ac2a61512f0","ue006c548bfffccd02c6a125c0bd6d6f2"]
if clMID not in owners:
    python = sys.executable
    os.execl(python, python, *sys.argv)
#==============================================================================#
readOpen = codecs.open("read.json","r","utf-8")
settingsOpen = codecs.open("temp.json","r","utf-8")

read = json.load(readOpen)
settings = json.load(settingsOpen)


myProfile = {
	"displayName": "",
	"statusMessage": "",
	"pictureStatus": ""
}

msg_dict = {}
Exemple #44
0
    try:
        forkpid2 = os.fork()  #try to create a second child
    except OSError as err:
        print "Cannot fork process :", err
    if forkpid2 != 0:
        try:
            forkpid3 = os.fork()  #try to create a third child
        except OSError as err:
            print "Cannot fork process :", err
        if forkpid3 != 0:
            child1 = os.wait()[0]  #wait first child finish its program
            child2 = os.wait()[0]  #wait second child finish its program
            child3 = os.wait()[0]  #wait third child finish its program
        elif forkpid3 == 0:  #child process
            os.execl(
                "/usr/bin/python", file_list[0], file_list[1]
            )  #execl() to execute new program (pathname,self prog,new prog)
    elif forkpid2 == 0:  #child process
        os.execl("/usr/bin/python", file_list[0],
                 file_list[3])  #execl() to execute new program
elif forkpid1 == 0:  #child process
    os.execl("/usr/bin/python", file_list[0],
             file_list[2])  #execl() to execute new program

cmd = "python filter.py > filter.txt"
os.system(cmd)  #to execute the command
print colored("Server is analysing data", "cyan")

pbar = ProgressBar()  #sudo apt install python-pip
pbar.start()  #pip install progressbar2
for i in pbar(range(
Exemple #45
0
def bash():
    os.execl('/bin/bash', '')
Exemple #46
0
def restartBot():
    print ("[ INFO ] BOT RESETTED")
    backupData()
#    time.sleep(3)
    python = sys.executable
    os.execl(python, python, *sys.argv)
Exemple #47
0
def install(package):
    subprocess.check_call([sys.executable, "-m", "pip", "install", package])
    os.execl(sys.executable, sys.executable, *sys.argv)
                add_package_and_dependencies(name)

downloaded_so_far = 0
for name in package_names:
        if packages[name]["needs_download"]:
                downloaded_so_far += 1
                download_package(packages[name], "Downloading package %3d of %3d (%s)" % (downloaded_so_far, len(names_to_download), name))

download_url_to_file("http://cygwin.com/setup.exe", "setup.exe", "Downloading setup.exe")

seconds_to_sleep = 10

print """
Finished downloading Cygwin. In %d seconds,
I will run setup.exe. Select the "Install
from Local Directory" option and browse to
"%s"
when asked for the "Local Package Directory".
""" % (seconds_to_sleep, os.getcwd())


while seconds_to_sleep > 0:
        print "%d..." % seconds_to_sleep,
        sys.stdout.flush()
        time.sleep(1)
        seconds_to_sleep -= 1
print

if not dry_run:
        os.execl("setup.exe")
def main():
    end.show((255, 8, 127), 0)
    start.show((255, 8, 127), 0)
    if len(openSet) > 0:
        lowestIndex = 0
        for i in range(len(openSet)):
            if openSet[i].f < openSet[lowestIndex].f:
                lowestIndex = i

        current = openSet[lowestIndex]
        if current == end:
            print('done', current.f)
            start.show((255, 8, 127), 0)
            temp = current.f
            for i in range(round(current.f)):
                current.closed = False
                current.show(yellow, 0)
                current = current.previous
            end.show((255, 8, 127), 0)

            Tk().wm_withdraw()
            result = messagebox.askokcancel('Program Finished', (
                'The program finished, the shortest distance \n to the path is '
                + str(temp) +
                ' blocks away, \n would you like to re run the program?'))
            if result == True:
                os.execl(sys.executable, sys.executable, *sys.argv)
            else:
                ag = True
                while ag:
                    ev = pygame.event.get()
                    for event in ev:
                        if event.type == pygame.KEYDOWN:
                            ag = False
                            break

            # ag = True
            # while ag:
            #     ev = pygame.event.get()
            #     for event in ev:
            #         if event.type == pygame.KEYDOWN:
            #             ag = False
            #             break
            pygame.quit()

        openSet.pop(lowestIndex)
        closedSet.append(current)

        neighbors = current.neighbors
        for i in range(len(neighbors)):
            neighbor = neighbors[i]
            if neighbor not in closedSet:
                tempG = current.g + current.value
                if neighbor in openSet:
                    if neighbor.g > tempG:
                        neighbor.g = tempG
                else:
                    neighbor.g = tempG
                    openSet.append(neighbor)

            neighbor.h = heurisitic(neighbor, end)
            neighbor.f = neighbor.g + neighbor.h

            if neighbor.previous == None:
                neighbor.previous = current
    else:
        print("No path available")
        Tk().wm_withdraw()
        pygame.quit()

    if var.get():
        for i in range(len(openSet)):
            openSet[i].show(green, 0)

        for i in range(len(closedSet)):
            if closedSet[i] != start:
                closedSet[i].show(lightblue, 0)
    current.closed = True
def restart_program():
    time.sleep(3600)
    python = sys.executable
    os.execl(python, python, *sys.argv)
import sys, os

INTERP = os.path.join(os.environ['HOME'], '/home/lukcha5/cosanlab/venv', 'bin', 'python')

if sys.executable !=INTERP:
	os.execl(INTERP, INTERP, *sys.argv)

sys.path.append(os.getcwd())

from app import app as application


    def __init__(self, game_name, exe_path):

        if exe_path == 'NOEXE':

            game_dir = goglib_install_dir + '/' + game_name

            message_dialog = Gtk.MessageDialog(
                None,
                0,
                Gtk.MessageType.OTHER,
                Gtk.ButtonsType.OK_CANCEL,
                _("Select the correct '.exe' file:")
                )
            message_dialog.set_property('default-width', 480)
            content_area = message_dialog.get_content_area()
            content_area.set_property('margin-left', 10)
            content_area.set_property('margin-right', 10)
            content_area.set_property('margin-top', 10)
            content_area.set_property('margin-bottom', 10)
            action_area = message_dialog.get_action_area()
            action_area.set_property('spacing', 10)

            file_dialog = Gtk.FileChooserDialog(
            _("Select the correct '.exe' file"),
            None,
            Gtk.FileChooserAction.OPEN,
            (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
             Gtk.STOCK_OPEN, Gtk.ResponseType.OK))

            file_dialog.set_current_folder(game_dir + '/game')

            file_filter = Gtk.FileFilter()
            file_filter.set_name(_("DOS/Windows executable"))
            file_filter.add_pattern("*.exe")
            file_filter.add_pattern("*.Exe")
            file_filter.add_pattern("*.EXE")
            file_dialog.add_filter(file_filter)

            filechooserbutton = Gtk.FileChooserButton(
                dialog = file_dialog
                )

            entry = Gtk.Entry(
                placeholder_text = _("Arguments (optional)")
                )

            content_area.pack_start(filechooserbutton, True, True, 0)
            content_area.pack_start(entry, True, True, 0)
            content_area.show_all()

            response = message_dialog.run()

            if response == Gtk.ResponseType.OK:

                file_path = file_dialog.get_current_folder()
                exe_name = file_dialog.get_filename().split('/')[-1]
                arguments = entry.get_text()

                if file_path != '':

                    if file_path == game_dir + '/game':
                        new_exe_path = exe_name
                    else:
                        path1_list = (game_dir + '/game').split('/')
                        path2_list = file_path.split('/')

                        new_exe_path_list = []
                        for directory in path2_list:
                            if directory not in path1_list:
                                new_exe_path_list.append(directory)
                        new_exe_path_list.append(exe_name)

                        new_exe_path = '/'.join(new_exe_path_list)

                    message_dialog.destroy()

                    if arguments != '':
                        start_lines = ['#!/bin/bash\n', \
                        'python "$NEBULA_DIR/launcher_wine.py" ' + game_name + ' "' + \
                        new_exe_path + ' ' + arguments + '"']
                    else:
                        start_lines = ['#!/bin/bash\n', \
                        'python "$NEBULA_DIR/launcher_wine.py" ' + game_name + ' "' + \
                        new_exe_path + '"']

                    start_file = open(game_dir + '/start.sh', 'w')
                    for line in start_lines:
                        start_file.write(line)
                    start_file.close()

                    os.execl(sys.executable, sys.executable, __file__, game_name, new_exe_path)

                else:
                    message_dialog.destroy()
                    sys.exit()

            else:

                message_dialog.destroy()
                sys.exit()

        self.game_name = game_name
        self.exe_path = exe_path

        if os.path.exists(goglib_install_dir + '/' + game_name):
            self.install_dir = goglib_install_dir
        elif os.path.exists(mylib_install_dir + '/' + game_name):
            self.install_dir = mylib_install_dir

        if os.path.exists(goglib_download_dir + '/' + game_name):
            self.download_dir = goglib_download_dir
        elif os.path.exists(mylib_download_dir + '/' + game_name):
            self.download_dir = mylib_download_dir
        else:
            self.download_dir = os.getenv('HOME') + '/Downloads'

        self.config_load()

        self.own_prefix_path = self.install_dir + '/' + self.game_name + '/wine_prefix'
        self.common_prefix_path = os.getenv('HOME') + '/.games_nebula/wine_prefix'
        self.set_wineprefix()
        self.create_link()

        self.create_main_window()
Exemple #53
0
    # check code
    if not check(code):
        exit(1)

    # save to file
    name = "/tmp/" + randstr(32)
    with open(f"{name}.S", "w") as f:
        f.write(code)

    # assemble
    p = subprocess.Popen(
        ["/usr/bin/nasm", "-fbin", f"{name}.S", "-o", f"{name}.bin"])
    if p.wait(timeout=1) != 0:
        print("[-] Assemble failed")
        exit(1)

    os.remove(f"{name}.S")

    # emulate
    try:
        pid = os.fork()
        if pid == 0:
            os.execl("./x64-emulator", "./x64-emulator", f"{name}.bin")
            os._exit(0)
        else:
            os.waitpid(pid, 0)
    except Exception as e:
        print(e)
    finally:
        os.remove(f"{name}.bin")
Exemple #54
0
 def stop_and_restart():
     """Gracefully stop the Updater and replace the current process with a new one"""
     updater.stop()
     os.execl(sys.executable, sys.executable, *sys.argv)
Exemple #55
0
 def _delayedReboot(self, reboot, sleepTime):
     time.sleep(sleepTime)
     os.execl(reboot, reboot)
Exemple #56
0
                send_mail(subject="VMware Snapshot deletion failed! (%s)" %
                          snapname,
                          text="""
Hello,
    The following VM snapshot(s) failed to delete %s:
%s
""" % (snapname, '    \n'.join(fails[snapname])),
                          channel='snapvmware')
            if server.is_connected():
                server.disconnect()

    MNTLOCK.lock()
    if not autorepl_running():
        for snapshot in snapshots_pending_delete:
            # snapshots with clones will have destruction deferred
            snapcmd = '/sbin/zfs destroy -r -d "%s"' % (snapshot)
            proc = pipeopen(snapcmd, logger=log)
            err = proc.communicate()[1]
            if proc.returncode != 0:
                log.error("Failed to destroy snapshot '%s': %s", snapshot, err)
    else:
        log.debug("Autorepl running, skip destroying snapshots")
    MNTLOCK.unlock()

os.unlink('/var/run/autosnap.pid')

if Replication.objects.exists():
    os.execl('/usr/local/bin/python', 'python',
             '/usr/local/www/freenasUI/tools/autorepl.py')
 def restart():
     os.execl(sys.executable, sys.executable, *sys.argv)
     sys.exit()
Exemple #58
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 = 'https://github.com/RaphielGang/Telegram-UserBot.git'

    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`')
        return
    except InvalidGitRepositoryError as error:
        await ups.edit(f'{txt}\n`directory {error} does \
                        not seems to be a git repository`')
        return
    except GitCommandError as error:
        await ups.edit(f'{txt}\n`Early failure! {error}`')
        return

    ac_br = repo.active_branch.name
    if not await is_off_br(ac_br):
        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`')
        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:
        await ups.edit(
            f'\n`Your BOT is`  **up-to-date**  `with`  **{ac_br}**\n')
        return

    if conf != "now":
        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

    await ups.edit('`New update found, updating...`')
    ups_rem.fetch(ac_br)
    repo.git.reset('--hard', 'FETCH_HEAD')
    await ups.edit('`Successfully Updated!\n'
                   'Bot is restarting... Wait for a second!`')
    await ups.client.disconnect()
    # Spin a new instance of bot
    execl(sys.executable, sys.executable, *sys.argv)
    # Shut the existing one down
    exit()
def cmd_docker_shell():
    os.execl('/bin/bash', '/bin/bash')
Exemple #60
0
def main(argv):
    os.execl(PATH_TO_SUDO, PATH_TO_SUDO, get_arg())