Пример #1
0
def run_deploy(**kwargs):
    euid = os.geteuid()
    if euid != 0:
        print ("Script not started as root. Running sudo..")
        args = ['sudo', sys.executable] + sys.argv + [os.environ]
        # the next line replaces the currently-running process with the sudo
        os.execlpe('sudo', *args)
        return

    if not skip_nginx:
        link = '/etc/nginx/sites-enabled/%s' % os.path.basename(nginx_conf)
        if not os.path.islink(link):
            os.symlink(nginx_conf, link)
        else:
            if overwrite:
                os.unlink(link)
                os.symlink(nginx_conf, link)

    if not skip_uwsgi:
        link = '/etc/systemd/system/%s' % os.path.basename(uwsgi_emperor)
        if not os.path.islink(link):
            os.symlink(uwsgi_emperor, link)
        else:
            if overwrite:
                os.unlink(link)
                os.symlink(uwsgi_emperor, link)
Пример #2
0
def enter_build_environment(platform,
                            arch,
                            sourcedir=None,
                            bash_completions=None,
                            env=None):
    '''
    Enters to a new shell with the build environment
    '''
    BASHRC = '''
if [ -e ~/.bashrc ]; then
source ~/.bashrc
fi
%s
PS1='\[\033[01;32m\][cerbero-%s-%s]\[\033[00m\]%s'
BASH_COMPLETION_SCRIPTS="%s"
BASH_COMPLETION_PATH="$CERBERO_PREFIX/share/bash-completion/completions"
for f in $BASH_COMPLETION_SCRIPTS; do
  [ -f "$BASH_COMPLETION_PATH/$f" ] && . "$BASH_COMPLETION_PATH/$f"
done
'''
    MSYSBAT = '''
start bash.exe --rcfile %s
'''
    if sourcedir:
        sourcedirsh = 'cd ' + sourcedir
    else:
        sourcedirsh = ''
    if bash_completions is None:
        bash_completions = set()

    ps1 = os.environ.get('PS1', '')

    env = os.environ.copy() if env is None else env

    if PLATFORM == Platform.WINDOWS:
        msysbatdir = tempfile.mkdtemp()
        msysbat = os.path.join(msysbatdir, "msys.bat")
        bashrc = os.path.join(msysbatdir, "bash.rc")
        with open(msysbat, 'w+') as f:
            f.write(MSYSBAT % bashrc)
        with open(bashrc, 'w+') as f:
            f.write(
                BASHRC %
                (sourcedirsh, platform, arch, ps1, ' '.join(bash_completions)))
        subprocess.check_call(msysbat, shell=True, env=env)
        # We should remove the temporary directory
        # but there is a race with the bash process
    else:
        bashrc = tempfile.NamedTemporaryFile()
        bashrc.write((BASHRC % (sourcedirsh, platform, arch, ps1,
                                ' '.join(bash_completions))).encode())
        bashrc.flush()
        shell = os.environ.get('SHELL', '/bin/bash')
        if os.system("%s --rcfile %s -c echo 'test' > /dev/null 2>&1" %
                     (shell, bashrc.name)) == 0:
            os.execlpe(shell, shell, '--rcfile', bashrc.name, env)
        else:
            env["CERBERO_ENV"] = "[cerbero-%s-%s]" % (platform, arch)
            os.execlpe(shell, shell, env)
        bashrc.close()
Пример #3
0
def get_root():
    euid = os.geteuid()
    if euid != 0:
        print '[-] You didn\'t run as root!'
        print '[-] Running sudo now...'
        args = ['sudo', sys.executable] + sys.argv + [os.environ]
        os.execlpe('sudo', *args)
Пример #4
0
def isRoot():
    euid = os.geteuid()
    if euid != 0:
        print("Script not started as root. Running sudo..")
        args = ['sudo', sys.executable] + sys.argv + [os.environ]
        os.execlpe('sudo', *args)
    return True
Пример #5
0
 def do_zipd(self, inp):
     file_list = []
     for file in os.listdir(os.getcwd()):
         if not os.path.isfile(os.path.join(
                 os.getcwd(), file)) and not file.startswith('.'):
             file_list.append(file)
     questions = [
         inquirer.Checkbox(
             'files',
             message=
             "Select Folders to Zip (use Spacebar to select and Enter to confirm)",
             choices=file_list)
     ]
     answers = inquirer.prompt(questions)
     try:
         zipf = ZipFile("MyShellPy.zip", 'w')
         for dir in answers['files']:
             for root, dirs, files in os.walk(dir):
                 for file in files:
                     zipf.write(
                         os.path.join(root, file),
                         os.path.relpath(os.path.join(root, file),
                                         os.path.join(dir, '..')))
         zipf.close()
         print('All file(s) zipped successfully!')
     except PermissionError:
         print("Requires Root Access")
         args = ['sudo', sys.executable] + sys.argv + [os.environ]
         os.execlpe('sudo', *args)
Пример #6
0
def Run():
    import os
    import os.path as osp
    import sys
    import subprocess
    import json

    name = osp.basename(sys.argv[0])
    notebook = sys.argv[1]

    if name == 'jpy':
        script = notebook.replace('.ipynb', '.py')
        if not osp.exists(
                script) or osp.getmtime(notebook) > osp.getmtime(script):
            subprocess.call([
                'jupyter', 'nbconvert', '--log-level', '0', '--to', 'script',
                notebook
            ])
        os.execlp('ipython3', script, script, *sys.argv[2:])

    elif name == 'jpn':
        env = os.environ
        env['IPYTHONARGV'] = json.dumps(sys.argv[2:])
        os.execlpe('jupyter', 'jupyter', 'nbconvert', '--execute',
                   '--ExecutePreprocessor.timeout=600', '--inplace', '--to',
                   'notebook', notebook, '--output', notebook, env)
Пример #7
0
def port_testing(name, portv='27'):
    """ Port Testing function for various phase implementations """
    euid = os.geteuid()
    if euid:
        args = ['sudo', sys.executable] + sys.argv + [os.environ]
        os.execlpe('sudo', *args)

    for phase in [
            port_fetch, port_checksum, port_extract, port_configure,
            port_build, port_destroot, port_clean
    ]:
        print((phase.__name__))
        phase_output = phase(name, portv)
        if phase_output:
            print((phase.__name__ + " - SUCCESS"))
        else:
            print((phase.__name__ + " FAILED"))
            port_clean(name, portv)
            print("Exiting")
            sys.exit(1)

        euid = os.geteuid()
        if euid:
            args = ['sudo', sys.executable] + sys.argv + [os.environ]
            os.execlpe('sudo', *args)
Пример #8
0
def run_docker_container(
    container_name,
    volumes,
    environment,
    docker_img,
    docker_cmd,
    dry_run,
    nvidia,
    docker_memory_limit,
    docker_cpu_limit,
) -> int:

    docker_run_args = dict(
        container_name=container_name,
        volumes=volumes,
        env=environment,
        docker_img=docker_img,
        docker_cmd=docker_cmd,
        nvidia=nvidia,
        docker_memory_limit=docker_memory_limit,
        docker_cpu_limit=docker_cpu_limit,
    )
    docker_run_cmd = get_docker_run_cmd(**docker_run_args)

    if dry_run:
        print(json.dumps(docker_run_cmd))
        return 0

    os.execlpe("paasta_docker_wrapper", *docker_run_cmd)
    return 0
Пример #9
0
def main():
    cmd = sys.argv[1:]
    n_gpus = 1
    if len(sys.argv) >= 3 and sys.argv[1] == '-n':
        n_gpus = int(sys.argv[2])
        cmd = sys.argv[3:]

    def is_free(gpu):
        return len(gpu.processes) == 0

    gpus = new_query()
    memory_used = [(gpu.memory_used, gpu.index) for gpu in gpus
                   if is_free(gpu)]

    if len(memory_used) < n_gpus:
        print("sorry, there are not enough free gpus right now :(")
        exit(1)

    memory_used.sort()
    indices = [str(idx) for mu, idx in memory_used[:n_gpus]]

    env = os.environ
    env['CUDA_VISIBLE_DEVICES'] = ','.join(indices)

    os.execlpe(cmd[0], *cmd, env)
Пример #10
0
def get_auth():
    euid = os.geteuid()
    if euid != 0:
        args = ['sudo', sys.executable] + sys.argv + [os.environ]
        # replaces the currently-running process with the sudo
        os.execlpe('sudo', *args)
    return euid == 0
Пример #11
0
def run():
    if back_end.Debug:
        # Running program without root for convenience

        # old_file = back_end.OldFile()
        # old_file.run_old_file()
        win = LinuxProgram()
        win.connect("delete-event", Gtk.main_quit)
        win.show_all()
        Gtk.main()

    else:
        # following code taken from
        # http://stackoverflow.com/questions/5222333/authentication-in-python-script-to-run-as-root
        # tests if the program is running as root, needs to run as root, needs to run as root to
        # execute sudo commands
        euid = os.geteuid()
        if euid != 0:
            print("Program not started as root. Running sudo..")
            args = ['sudo', sys.executable] + sys.argv + [os.environ]
            # the next line replaces the currently-running process with the sudo
            os.execlpe('sudo', *args)

        print('Running as root successful!!')

        win = LinuxProgram()
        win.connect("delete-event", Gtk.main_quit)
        win.show_all()
        Gtk.main()
Пример #12
0
def check_root():
    """Checks if script is executed with root privileges and if not tries to run as root (requesting password)"""
    if os.geteuid() != 0:
        print("Script not started as root. Running sudo..")
        args = ['sudo', sys.executable] + sys.argv + [os.environ]
        # the next line replaces the currently-running process with the sudo
        os.execlpe('sudo', *args)
Пример #13
0
def _require_root():
    root_mode = 'UBUP_STAGE_1' not in os.environ
    user_mode = 'UBUP_STAGE_1' in os.environ \
                and 'UBUP_STAGE_2' not in os.environ
    if root_mode or user_mode:
        launch_env = os.environ
        if root_mode:
            launch_env['UBUP_STAGE_1'] = '1'
        if user_mode:
            launch_env['UBUP_STAGE_2'] = '1'

        try:
            u = os.environ['SUDO_USER']
        except KeyError:
            u = os.environ['USER']

        args = ['sudo', '-E']
        if user_mode:
            args += ['-u', u]
        args += [sys.executable]

        if getattr(sys, 'frozen', False):
            # Running in a bundle created by PyInstaller
            # sys.executable already points to the bundle
            args += [launch_env]
        else:
            # Running in live mode. sys.executable points
            # to the Python interpreter
            args += sys.argv + [launch_env]

        # Replace the current process
        os.execlpe('sudo', *args)
Пример #14
0
 def run(self) -> int:
     cmd = self._resolve_command()
     if not cmd:
         logger.error("Command not found: %r", self._cmd)
         return errno.ENOENT
     # This should never return.
     os.execlpe(cmd, self._cmd, *self._args, self._env)
Пример #15
0
def test_errand_cmd(tile_repo, errand_name):
	print('test-errand is currently disabled while we work on improving it (issue #134)', file=sys.stderr)
	sys.exit(1)
	rendered_errand = erb.render(errand_name, tile_repo)
	env = os.environ
	env['PACKAGE_PATH'] = os.path.join(tile_repo, 'release/blobs')
	os.execlpe('bash', 'bash', rendered_errand, env)
Пример #16
0
def test_errand_cmd(tile_repo, errand_name):
	print('test-errand is currently disabled while we work on improving it (issue #134)', file=sys.stderr)
	sys.exit(1)
	rendered_errand = erb.render(errand_name, tile_repo)
	env = os.environ
	env['PACKAGE_PATH'] = os.path.join(tile_repo, 'release/blobs')
	os.execlpe('bash', 'bash', rendered_errand, env)
Пример #17
0
def check_permission():
    euid = os.geteuid()
    if euid != 0:
        print('Script not started as root. Running sudo..')
        args = ['sudo', sys.executable] + sys.argv + [os.environ]
        # the next line replaces the currently-running process with the sudo
        os.execlpe('sudo', *args)
Пример #18
0
def run_docker_container(
    container_name,
    volumes,
    environment,
    docker_img,
    docker_cmd,
    dry_run,
    nvidia,
):
    docker_run_args = dict(
        container_name=container_name,
        volumes=volumes,
        env=environment,
        docker_img=docker_img,
        docker_cmd=docker_cmd,
        nvidia=nvidia,
    )
    docker_run_cmd = get_docker_run_cmd(**docker_run_args)

    if dry_run:
        paasta_print(json.dumps(docker_run_cmd))
        return 0

    os.execlpe('paasta_docker_wrapper', *docker_run_cmd)
    return 0
Пример #19
0
 def do_zipf(self, inp):
     file_list = []
     for file in os.listdir(os.getcwd()):
         if os.path.isfile(os.path.join(os.getcwd(),
                                        file)) and not file.startswith('.'):
             file_list.append(file)
     questions = [
         inquirer.Checkbox(
             'files',
             message=
             "Select Files to Zip (use Spacebar to select and Enter to confirm)",
             choices=file_list)
     ]
     answers = inquirer.prompt(questions)
     print(answers['files'])
     try:
         with ZipFile(os.path.basename(os.getcwd()) + '.zip', 'w') as zip:
             for i in range(len(answers['files'])):
                 print(answers['files'][i])
                 zip.write(answers['files'][i])
             print('All file(s) zipped successfully!')
     except PermissionError:
         print("Requires Root Access")
         args = ['sudo', sys.executable] + sys.argv + [os.environ]
         os.execlpe('sudo', *args)
Пример #20
0
 def get_super_user_access(self):
     euid = os.geteuid()
     if euid != 0:
         print("Script not started as root. Running sudo..")
         args = ['sudo', sys.executable] + sys.argv + [os.environ]
         # the next line replaces the currently-running process with the sudo
         os.execlpe('sudo', *args)
         return True
Пример #21
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)
Пример #22
0
def aquireRoot():
	# Aquires root
	euid = geteuid()
	if euid != 0:
		print(ROOT_MESSAGE)
		print("Asking for root password...")
		args = ['sudo','-E', executable] + argv + [environ]
		execlpe('sudo', *args)
	print("\nAquired root!")
Пример #23
0
def main(username, password, interface, acid):
    if sys.platform.startswith("linux") or sys.platform.startswith("darwin"):
        euid = os.geteuid()
        if euid != 0:
            print("正在请求root权限以调用dhclient...")
            args = ["sudo", sys.executable] + sys.argv + [os.environ]
            os.execlpe("sudo", *args)

    print(login(username, password, interface, acid))
Пример #24
0
def runTestExeclpe():
    """ This should work; """
    # here you're replacing environment variable. uname will fail
    os.execlpe("test.sh", "MY PROOF", {"PATH":os.getcwd()})
    # here you're appending to PATH variable; comment above line
    os.execlpe("test.sh", "APPEND", {"PATH": os.environ["PATH"]+":"+os.getcwd()})
    # here I use a vector
    os.execvpe("test.sh", ["APPEND"], {"PATH": os.environ["PATH"]+":"+os.getcwd()})
    print "I SHOULD NEVER REACH THIS LINE"
Пример #25
0
def authenticate():
    '''Prompt the user for the superuser password if required.'''
    # The euid (effective user id) of the superuser is 0.
    euid = os.geteuid()
    if euid != 0:
        args = ['sudo', '-E', sys.executable] + sys.argv[:] + [os.environ]
        # Replaces the current running process with the sudo authentication.
        os.execlpe('sudo', *args)
    return True
Пример #26
0
def define_process_name():
    '''自定义python程序进程名'''
    procname = 'Hello'
    import os, sys
    if not os.environ.has_key('NEWPROCNAME'):
        os.execlpe(sys.executable, procname, __file__, {'NEWPROCNAME': procname})
    import dl
    libc = dl.open('/lib/libc.so.6')
    libc.call('prctl', 15, '%s\0' %procname, 0, 0, 0)
Пример #27
0
def set_root():
    euid = os.geteuid()
    if euid != 0:
        print colored("[!!] The installation process needs root privileges.."\
                , "red")
        args = ['sudo', sys.executable] + sys.argv + [os.environ]
        os.execlpe('sudo', *args)
    else:
        print colored("[!!] You already have permission to install!", "red")
Пример #28
0
def checkRoot():
    euid = os.geteuid()
    if euid != 0:
        print("Script not started as root. Running sudo..")
        args = ['sudo', sys.executable] + sys.argv + [os.environ]
        # the next line replaces the currently-running process with the sudo
        os.execlpe('sudo', *args)

    print('Running. Your euid is', euid)
Пример #29
0
    def check_sudo(self):
        euid = os.geteuid()
        if euid != 0:
            # How we run this script again depends if its a executable or not
            if getattr(sys, 'frozen', False):
                args = ['sudo', sys.executable] + sys.argv[1:] + [os.environ]
            else:
                args = ['sudo', sys.executable] + sys.argv + [os.environ]

            os.execlpe('sudo', *args)
Пример #30
0
    def check_sudo(self):
        euid = os.geteuid()
        if euid != 0:
            # How we run this script again depends if its a executable or not
            if getattr(sys, 'frozen', False):
                args = ['sudo', sys.executable] + sys.argv[1:] + [os.environ]
            else:
                args = ['sudo', sys.executable] + sys.argv + [os.environ]

            os.execlpe('sudo', *args)
 def run_payload(shell_command: str) -> None:
     pid = os.fork()
     if pid == 0:
         # We're the child
         args = shlex.split(shell_command)
         program = args[0]
         os.execlpe(program, *args, os.environ)
     else:
         # We're the parent
         os.waitpid(pid, 0)
Пример #32
0
	def onClickBtn1(self, button):
		euid = os.geteuid()
		if euid != 0:
			print("Script not started as root. Running sudo..")
			args = ['sudo', sys.executable] + sys.argv + [os.environ]
			# the next line replaces the currently-running process with the sudo
			os.execlpe('sudo', *args)

		print('Running. Your euid is', euid)
		'''bashCommand = "apt-get install mypaint"
Пример #33
0
def main():
    """Script function."""
    # Parsing arguments.
    parser = ArgumentParser(description='Network scanner.')
    parser.add_argument('addresses',
                        default=SUPPRESS,
                        help='Addresses to scan.')
    parser.add_argument('period', default=SUPPRESS, help='Period of scan.')
    parser.add_argument('dbase_path',
                        default=SUPPRESS,
                        help='Path to database file.')
    parser.add_argument('-v',
                        '--verbose',
                        help='Verbose output.',
                        action='store_true')
    args = parser.parse_args()

    # Checking root permissions (they are needed to send ARP packets.)
    euid = os.geteuid()
    if euid != 0:
        args = ['sudo', sys.executable] + sys.argv + [os.environ]
        os.execlpe('sudo', *args)

    # Logging config.
    logging_config = {'format': '%(asctime)s: %(message)s'}
    if args.verbose:
        logging_config['level'] = logging.INFO
    logging.basicConfig(**logging_config)

    # Initializing.
    loop = asyncio.get_event_loop()
    lock = asyncio.Lock()
    ending = asyncio.Future()
    scanner = partial(scanoperations.scan_arp, args.addresses)
    scanner_coro = partial(loop.run_in_executor, None, scanner)
    conn = sqlite3.connect(args.dbase_path)
    if not scanoperations.check_dbase(conn):
        scanoperations.init_dbase(conn)
    result_handler = partial(scanoperations.write_to_dbase,
                             conn=conn,
                             lock=lock)

    # Running scanner.
    try:
        scanning = scanoperations.scan_until_complete(loop, scanner_coro,
                                                      result_handler,
                                                      int(args.period), ending)
        loop.run_until_complete(scanning)
        loop.run_forever()
    except KeyboardInterrupt:
        ending.set_result(True)
        tasks = asyncio.Task.all_tasks()
        logging.info('Closing program, finishing scheduled tasks.')
        loop.run_until_complete(asyncio.gather(*tasks))
        logging.info('All tasks finished.')
Пример #34
0
def sudo():
    """
    Checks that the program is running as root, otherwise asks for permissions and it runs again.
    """
    euid = os.geteuid()
    if euid != 0:
        print("Script not started as root. Running sudo...")
        args = ['sudo', sys.executable] + sys.argv + [os.environ]
        os.execlpe('sudo', *args)  # Replaces the current process with the sudo

    print("Running as sudo")
Пример #35
0
def checkForAdmin():
    try:
        is_admin = os.getuid() == 0
        if not is_admin:
            print "Script not started as root. Running sudo.."
            args = ['sudo', sys.executable] + sys.argv + [os.environ]
            # the next line replaces the currently-running process with the sudo
            os.execlpe('gksudo', *args)

    except AttributeError:
        print 'this part of the code must be run on a Unix system only'
Пример #36
0
def rerun_as_root():
    """Replace the current process with itself running with root permissions.
    Prompt the user for their password to support this.
    """

    euid = os.geteuid()
    if euid == 0:
        return

    args = ['sudo', sys.executable] + sys.argv + [os.environ]
    os.execlpe('sudo', *args)
def daemon():

    euid = os.geteuid()
    if euid != 0:
        print "Script not started as root. Running sudo.."
        args = ['sudo', sys.executable] + sys.argv + [os.environ]
        # the next line replaces the currently-running process with the sudo
        os.execlpe('sudo', *args)

    print 'Running. Your euid is', euid
    daemonize(VNFManagerAdapter)
def daemon():

    euid = os.geteuid()
    if euid != 0:
        print "Script not started as root. Running sudo.."
        args = ['sudo', sys.executable] + sys.argv + [os.environ]
        # the next line replaces the currently-running process with the sudo
        os.execlpe('sudo', *args)

    print 'Running. Your euid is', euid
    daemonize(VNFManagerAdapter)
Пример #39
0
def main(argv):
    euid = os.geteuid()
    if euid != 0:
        print("Script did not started as root, running sudo..")
        args = ['sudo', sys.executable] + argv + [os.environ]
        # the next row replaces the currently-running process with the sudo
        os.execlpe('sudo', *args)

        scripts_path = os.path.dirname(os.path.abspath(__file__))

        out = __live_execute([os.path.join(scripts_path, 'io_manager.py'),
                               "-k"])
Пример #40
0
def sudo_check():
    euid = os.geteuid()
    if euid != 0:
        args = ['sudo - ', sys.executable] + sys.argv + [os.environ]
        os.execlpe('sudo', *args)

    if euid != 0:
        print "Sorry, you need to have root privileges to run this script"
        sys.exit()
    else:
        os.system('cls' if os.name == 'nt' else 'clear')
        print colour.OKGREEN + "You are running this script as root" + colour.ENDC
Пример #41
0
def run_as_root():

    if not running_as_root():

        args = ['sudo', sys.executable] + sys.argv + [os.environ]

        try:
            os.execlpe('sudo', *args)

        except Exception as e:

            print(e)
            sys.exit(1)
Пример #42
0
def elevate_privileges():
  # Modified from http://stackoverflow.com/a/5222710/369021
  sudo_exit_code = 0
  with open(os.devnull, 'w') as fnull:
    sudo_exit_code = subprocess.call(["sudo", "-n", "false"])
  # Exit code is 1 if `false` ran. 0 otherwise
  if sudo_exit_code == 0:
    print("Elevating Privileges. Please enter your password ...")
    # Relaunch using sudo.'-E',
    args = ['sudo', '-E', sys.executable] + sys.argv + ["--elevated"] + [os.environ]
    os.execlpe(*args);
  else:
    print("Running as Sudo")
	def __init__(self) :
		self.__platform = "macos" if platform.system().lower() == "darwin" else platform.system().lower()
		self.__setDefaultsSystem()
		self.currentPathScript = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))

		self.confFile = self.currentPathScript + os.sep + self.confFile

		if self.__platform != "windows" :
			if os.getenv("SUDO_USER") :
				self.originalUser = getpwnam(os.getenv("SUDO_USER"))
			else :
				self.originalUser = pwd.getpwuid(os.getuid())

			#Set sudo	
			euid = os.geteuid()
			if euid != 0:
			    args = ['sudo', sys.executable] + sys.argv + [os.environ]
			    print "* You must be root to change the hosts file, enter the password of root if prompted\n"		
			    os.execlpe('sudo', *args)

		if not os.path.isfile(self.confFile) :	
   			print "Configuration file doesn't exists, create now."
   			self.createConfiguration()

   		#Start configs	
		confs = open(self.confFile, 'r')
		dictConfig = { 'windows' : {}, 'macos' : {}, 'linux' : {} }
		for conf in confs : 
			if ("conf") in conf :
				m = re.match('conf\.([a-z]+)\.([a-z]+) ?= ?"(.*)"', conf.strip())
				dictConfig[m.group(1)][m.group(2)] = m.group(3)
				
		confs.close()

		#Update configs
		self.conf.update(dictConfig)
		
		#Set environment
		self.envir = self.conf[self.__platform]

		#Verify if exists configs for this OS
		if not self.envir:
			print "You don't have a configuration for your system! Add to file configuration."
			exit(1)

		#Set Separator for system	
		self.envir['pathseparator'] = os.sep

		#Makups for virtualhost
		self.initMarkupVhosts = '<VirtualHost *:80>'
		self.endMarkupVhosts = '</VirtualHost>'	
Пример #44
0
def setprocname(procname, libc='/lib/libc.so.6', env='__PROCNAME', format='%s:'):
	import os, sys
	if not os.environ.has_key(env):
		kw = dict(os.environ); kw[env] = procname
		os.execlpe(*([sys.executable, format%procname] + sys.argv + [kw]))

	import dl
	libc = dl.open(libc)

	platform = sys.platform.upper()
	if 'LINUX' in platform:
		libc.call('prctl', 15, '%s\0' %procname, 0, 0, 0)
	elif 'BSD' in platform:
		libc.call('setproctitle', '%s\0' %procname)
Пример #45
0
def setprocname(procname, key='__PROCNAME', format='%s '):
    if not os.environ.has_key(key):
        environ = dict(os.environ)
        environ[key] = procname
        os.execlpe(*([sys.executable, format % procname] + \
                      sys.argv + [environ]))
    where = find_library('c')
    assert where, 'setprocname needs libc installed.'
    libc = CDLL(where)
    procname = create_string_buffer(procname)
    platform = sys.platform.upper()
    if 'LINUX' in platform:
        libc.prctl(15, procname, 0, 0, 0)
    elif 'BSD' in platform:
        libc.setproctitle(procname)
Пример #46
0
def check_if_sudo():
    '''
    Checks if the process is running as root/sudo, and if not, it asks
    for the password
    '''
    
    # http://stackoverflow.com/questions/5222333/authentication-in-python-script-to-run-as-root
    euid = os.geteuid()
    if euid != 0: # root
        logging.warn("Script not started as root. Running sudo..")
        print '##################################################'
        print '### Script not started as root. Running sudo.. ###'
        print '##################################################'
        args = ['sudo', sys.executable] + sys.argv + [os.environ]
        # the next line replaces the currently-running process with the sudo
        os.execlpe('sudo', *args)
Пример #47
0
def rwabugiri_main(argv):
  pcks  = os.path.join(os.getcwd(), 'packages')
  env   = os.environ
  env.update({'PYTHONPATH': pcks})
  argl  = argv
  argl.append(env)
  return os.execlpe('python', *argl)
Пример #48
0
def start_process(cmd, target, env, *args):

    try:
        pid = os.fork()
    except OSError as e:
        logger.error(repr(e) + ' while fork')
        raise

    if pid == 0:
        _close_fds()
        args = list(args)
        env = dict(os.environ, **env)
        args.append(env)
        os.execlpe(cmd, cmd, target, *args)
    else:
        _waitpid(pid)
Пример #49
0
def setprocname(procname, env="__PROCNAME", format="%s "):
    import os, sys

    if not os.environ.has_key(env):
        environ = dict(os.environ)
        environ[env] = procname
        os.execlpe(*([sys.executable, format % procname] + sys.argv + [environ]))
    import ctypes, ctypes.util

    libc = ctypes.CDLL(ctypes.util.find_library("c"))
    procname = ctypes.create_string_buffer(procname)
    platform = sys.platform.upper()
    if "LINUX" in platform:
        libc.prctl(15, procname, 0, 0, 0)
    elif "BSD" in platform:
        libc.setproctitle(procname)
Пример #50
0
    def subshell(self, godir, *gopath):
        version = self.version
        if gopath:
            gopath = ":".join(gopath)

        goroot = os.path.join(godir, "go")
        gobin = os.path.join(goroot, "bin")
        newpath = ":".join([gobin, os.environ.get("PATH", "")])

        additionalenv = {
                "PATH": newpath,
                "GOROOT": goroot,
                "GOPATH": gopath,
                "GOENV": version,
        }
        newenv = os.environ.copy()
        newenv.update(**additionalenv)
        os.execlpe(os.environ.get("SHELL", '/bin/bash'), "", newenv)
Пример #51
0
    def start_workrave(self, instance, clean = True):

        name = "workrave" + str(instance)
        tmpdir = "/tmp/" + name + "/"
        pidfile = tmpdir + "pid"
        cwd = os.getcwd();

        env = os.environ
        env["WORKRAVE_TEST"]="1"
        env["WORKRAVE_FAKE"]="1"
        env["WORKRAVE_DBUS_NAME"] = "org.workrave.Workrave" + str(instance)
        env["WORKRAVE_HOME"] = tmpdir
        env["WORKRAVE_GCONF_ROOT"] = "/apps/" + name + "/";

        if clean:
            try:
                os.system("rm -rf " + tmpdir + ".workrave");
                os.mkdir(tmpdir)
            except:
                pass

        newpid = os.fork()
        if newpid == 0:
            out_log = file(name + ".out", 'w+')
            dev_null = file('/dev/null', 'r')

            os.dup2(out_log.fileno(), sys.stdout.fileno())
            os.dup2(out_log.fileno(), sys.stderr.fileno())
            os.dup2(dev_null.fileno(), sys.stdin.fileno())
            
            os.execlpe("/sbin/start-stop-daemon",
                       "/sbin/start-stop-daemon",               
                       "--quiet",
                       "--start",
                       "--pidfile", pidfile,
                       "--make-pidfile",
                       "--exec",
                       #"/usr/bin/valgrind",
                       #"--", "-v", "--trace-children=yes", "--leak-check=full",
                       #"--show-reachable=yes",
                       #"--log-file=" + cwd +"/val." + str(instance),  
                       cwd + "/frontend/text/src/workrave",
                       env)
Пример #52
0
    def fork_and_monitor( self, args ):
        """Fork a child process with same command line arguments except the
        ``-m`` switch. Monitor and reload the child process until normal
        exit."""
        while True :
            self.pa.logdebug( "Forking monitor ..." )
            pid = os.fork()
            if pid == 0 :   # child process
                cmdargs = sys.argv[:]
                cmdargs.remove( '-m' )
                cmdargs.append( os.environ )
                h.reseed_random()
                os.execlpe( sys.argv[0], *cmdargs )

            else :          # parent 
                try :
                    pid, status = os.wait()
                    if status & 0xFF00 != 0x300 :
                        sys.exit( status )
                except KeyboardInterrupt :
                    sys.exit(0)
Пример #53
0
def Run():
    import os
    import os.path as osp
    import sys
    import subprocess
    import json
    
    name = osp.basename(sys.argv[0])
    notebook = sys.argv[1]
    
    if name == 'jpy':
        script = notebook.replace('.ipynb', '.py')
        if not osp.exists(script) or osp.getmtime(notebook) > osp.getmtime(script):
            subprocess.call(['jupyter', 'nbconvert', '--log-level', '0', '--to', 'script', notebook])
        os.execlp('ipython3', script, script, *sys.argv[2:])
        
    elif name == 'jpn':
        env = os.environ
        env['IPYTHONARGV'] = json.dumps(sys.argv[2:])
        os.execlpe('jupyter', 'jupyter', 'nbconvert', '--execute', '--ExecutePreprocessor.timeout=600', 
                   '--inplace', '--to', 'notebook', notebook, '--output', notebook, env)
Пример #54
0
def main():
    if os.getenv("TMUX") is None:
        if os.getenv("SSH_TTY") is not None:
            if os.getenv("SSH_AUTH_SOCK") is not None:
                sock_file = os.path.join(os.getenv("HOME"), ".wrap_auth_sock")
                try:
                    #always try to remove
                    os.remove(sock_file)
                except OSError:
                    pass
                os.symlink(os.getenv("SSH_AUTH_SOCK"), sock_file)
                os.environ['SSH_AUTH_SOCK'] = sock_file

        try:
            subprocess.check_call(["tmux", "attach-session", "-t", "sshwrap"])
        except subprocess.CalledProcessError:
            os.environ['STY'] = "tmux-sshwrap"
            env = {k: os.environ[k] for k in os.environ.keys() if is_valid(k)}
            os.execlpe("tmux", "tmux", "new-session", "-s", "sshwrap", env)
    else:
        print('TMUX var is set...')
def main():
    """
    Program driver; checks if program is started as
    root and prompts for password if necessary; opens
    times.txt and runs necessary functions.
    """
    euid = os.geteuid()
    if euid != 0:
        print("Script not started as root. Running sudo..")
        args = ['sudo', sys.executable] + sys.argv + [os.environ]
        # the next line replaces the currently-running process with the sudo
        os.execlpe('sudo', *args)
    print('Running. Your euid is', euid)

    file = open('./cpu_output_files/times.txt', 'w+')
    freq = get_frequency()
    trace_runs(file, freq)
    print('Finished.')
    reset_freq = Popen(['sudo', 'cpufreq-set', '-c', '0', '-f',
             (str(freq) + 'Ghz')])
    reset_freq.communicate()
    print("Frequency reset.")
Пример #56
0
        # self.text.show()

        window.show_all()

def main():
    gtk.main()

if __name__ == "__main__":
    # to run as root
    euid = os.getuid()
    if euid != 0:
        print "You need root permissions"
        args = ['gksudo', sys.executable] + sys.argv + [os.environ]
        # the next line replaces the currently-running process with the sudo
        os.execlpe('gksudo', *args)
    print 'Running. Your euid is', euid
    # process files are usually in /proc/, so we test if the cron process exists
    PROCESSNAME = "cron"
    PROCESSRUNNING = False
    # test crond for redhat systems
    for process in psutil.process_iter():
        if process.name == PROCESSNAME:
            print "Cron process running...."
            PROCESSRUNNING = True
    if PROCESSRUNNING == True:
        CronWrite()
        main()

    else:
        print "Cron not running on your system, Please try running 'sudo service cron start'"
Пример #57
0
            print("'nanshe.egg-info' does not exist -- can't clean it")

setup(
    name="nanshe",
    version=versioneer.get_version(),
    description="An image processing toolkit.",
    url="https://github.com/jakirkham/nanshe",
    license="GPLv3",
    author="John Kirkham",
    author_email="*****@*****.**",
    scripts=glob("bin/*"),
    py_modules=["versioneer"],
    packages=find_packages(exclude=["tests*"]),
    cmdclass=dict(sum([_.items() for _ in [
        versioneer.get_cmdclass(),
        {"test": NoseTestCommand}
    ]], [])),
    build_requires=build_requires,
    install_requires=install_requires,
    tests_require=tests_require,
    test_suite="nose.collector",
    zip_safe=True
)

if sphinx_build_pdf:
    make_cmd = os.environ.get("MAKE", "make")
    cwd = os.getcwd()
    os.chdir("build/sphinx/latex")
    os.execlpe(make_cmd, "all", os.environ)
    os.chdir(cwd)
Пример #58
0
#!/usr/bin/python

import os, sys

euid = os.geteuid()
if euid != 0:
    print "Changing user to root..."
    args = ['sudo', sys.executable] + sys.argv + [os.environ]
    os.execlpe('sudo', *args)

print "****************************************"
print "*  Install Big Digital Clock"
print "****************************************"
print ""

print "Installing Application..."

print "Installing Service..."