예제 #1
0
파일: cmdconnect.py 프로젝트: sii/siptrack
 def _connectSSHLocal(self, hostname, username, passwd):
     sshcmd = [self.ssh_bin, '%s@%s' % (username, hostname)]
     if self.ssh_extraopt:
         sshcmd += self.ssh_extraopt.split()
     self.addStringToClipboard(passwd)
     pid, self.remote_fd = pty.fork()
     if pid == pty.CHILD:
         os.execlp(sshcmd[0], *sshcmd)
     try:
         mode = tty.tcgetattr(pty.STDIN_FILENO)
         tty.setraw(pty.STDIN_FILENO)
         restore = True
     except tty.error:
         restore = False
     signal.signal(signal.SIGWINCH, self._winchHandler)
     self._setRemoteTTYSize(self.remote_fd)
     self._setTerminalTitle('%s@%s' % (username, hostname))
     try:
         self._copySSHData(self.remote_fd, passwd)
     except (IOError, OSError):
         pass
     except:
         if restore:
             tty.tcsetattr(pty.STDIN_FILENO, tty.TCSAFLUSH, mode)
         raise
     if restore:
         tty.tcsetattr(pty.STDIN_FILENO, tty.TCSAFLUSH, mode)
     signal.signal(signal.SIGWINCH, signal.SIG_DFL)
     os.close(self.remote_fd)
예제 #2
0
파일: pty.py 프로젝트: freenas/py-bsd
def spawn(argv, master_read=_read, stdin_read=_read):
    """Create a spawned process."""
    if type(argv) == type(''):
        argv = (argv,)
    pid, master_fd = fork()
    if pid == CHILD:
        try:
            os.execlp(argv[0], *argv)
        except:
            # If we wanted to be really clever, we would use
            # the same method as subprocess() to pass the error
            # back to the parent.  For now just dump stack trace.
            traceback.print_exc()
        finally:
            os._exit(1)
    try:
        mode = tty.tcgetattr(STDIN_FILENO)
        tty.setraw(STDIN_FILENO)
        restore = 1
    except tty.error:    # This is the same as termios.error
        restore = 0
    try:
        _copy(master_fd, master_read, stdin_read)
    except OSError:
        # Some OSes never return an EOF on pty, just raise
        # an error instead.
        pass
    finally:
        if restore:
            tty.tcsetattr(STDIN_FILENO, tty.TCSAFLUSH, mode)

    os.close(master_fd)
    return os.waitpid(pid, 0)[1]
def main():
    "Option parsing and launch latex_dir"
    usage = "%prog [-c nb_of_columns -w outtexfile] directory_list"
    parser = OptionParser(usage = usage)
    parser.add_option('-w', dest='outtexfile', type='string',
                      help='output latex file (default is dir/latex_dir.tex)')
    parser.add_option('-c', dest='column', type='int', default = 2,
                      help='number of columns of latex file: 1 or 2')
    parser.add_option('--eps', dest='eps', default=False, action='store_true',
                      help='use eps files instead of pdf')
    (options, args) = parser.parse_args()
    if not args:
        parser.print_help()
        exit(5)
    for directory in args:
        if not options.outtexfile:
            outfile_name = os.sep.join((directory,
                                        'latex_dir_%s.tex' % directory))
        else:
            outfile_name = options.outtexfile
        if options.column not in (1, 2):
            print("invalid number of columns")
            parser.print_help()
            exit(5)
        latex_dir(outfile_name, directory, options.column, eps=options.eps)
        #compile the tex file
        if options.eps:
            os.execlp('latex', 'latex', '-interaction=nonstopmode',
                      '-output-directory', directory, outfile_name)
        else:
            os.execlp('pdflatex', 'pdflatex', '-interaction=nonstopmode',
                      '-output-directory', directory, outfile_name)
예제 #4
0
    def execute(self):
        creator = make_creator(self.params.config,
                               storage_path=self.params.storage)
        cluster_name = self.params.cluster
        try:
            cluster = creator.load_cluster(cluster_name)
            cluster.update()
        except (ClusterNotFound, ConfigurationError) as ex:
            log.error("Setting up cluster %s: %s\n" %
                      (cluster_name, ex))
            return

        if self.params.ssh_to:
            try:
                nodes = dict((n.name,n) for n in cluster.get_all_nodes())
                frontend = nodes[self.params.ssh_to]
            except KeyError:
                raise ValueError(
                    "Hostname %s not found in cluster %s" % (self.params.ssh_to, cluster_name))
        else:
            frontend = cluster.get_frontend_node()
        host = frontend.connection_ip()
        username = frontend.image_user
        knownhostsfile = cluster.known_hosts_file if cluster.known_hosts_file \
                         else '/dev/null'
        sftp_cmdline = ["sftp",
                        "-o", "UserKnownHostsFile=%s" % knownhostsfile,
                        "-o", "StrictHostKeyChecking=yes",
                        "-o", "IdentityFile=%s" % frontend.user_key_private]
        sftp_cmdline.extend(self.params.sftp_args)
        sftp_cmdline.append('%s@%s' % (username, host))
        os.execlp("sftp", *sftp_cmdline)
예제 #5
0
    def do_install(self, datafilename):
        with open(datafilename, 'rb') as ifile:
            d = pickle.load(ifile)
        d.destdir = os.environ.get('DESTDIR', '')
        d.fullprefix = destdir_join(d.destdir, d.prefix)

        if d.install_umask is not None:
            os.umask(d.install_umask)

        try:
            d.dirmaker = DirMaker(self.lf)
            with d.dirmaker:
                self.install_subdirs(d) # Must be first, because it needs to delete the old subtree.
                self.install_targets(d)
                self.install_headers(d)
                self.install_man(d)
                self.install_data(d)
                restore_selinux_contexts()
                self.run_install_script(d)
        except PermissionError:
            if shutil.which('pkexec') is not None and 'PKEXEC_UID' not in os.environ:
                print('Installation failed due to insufficient permissions.')
                print('Attempting to use polkit to gain elevated privileges...')
                os.execlp('pkexec', 'pkexec', sys.executable, main_file, *sys.argv[1:],
                          '-C', os.getcwd())
            else:
                raise
def main():
    usage = "%prog -d dir [-c nb_of_columns -w outtexfile]"

    parser = OptionParser(usage = usage)
    parser.add_option("-d", dest = "dir", type = "string",
                      help = "directory to search for pdf files")
    parser.add_option("-w", dest = "outtexfile", type = "string",
                      help = "output latex file (default is dir/latex_dir.tex)")
    parser.add_option("-c", dest = "column", type = "int", default = 2,
            help = "number of columns of latex file: 1 or 2")
    (options, args) = parser.parse_args()

    if not options.dir:
        print "no directory given"
        parser.print_help()
        exit()
    if not options.outtexfile:
        outfile = open(os.sep.join((options.dir, 'latex_dir.tex')), 'w')
    else:
        outfile = open(options.outtexfile, 'w')
    if options.column not in (1, 2):
        print "invalid number of columns"
        parser.print_help()
        exit()

    latex_dir(outfile, options.dir, options.column)

    #compile the tex file
    os.execlp('pdflatex', 'pdflatex', '-interaction=nonstopmode',
           '-output-directory', options.dir, outfile.name)
예제 #7
0
    def forkShell(self):
        """
        Fork the current process and replace it with Bash.
        """
        try:
            childPID, fd = pty.fork()
        except OSError:
            msg = 'Could not spawn another terminal.'
            return None

        if childPID == 0:
            # We are in the child process: flush stdout to be safe.
            sys.stdout.flush()

            # Setup the environment variables for the new terminal.
            for key, value in self.envVars.items():
                os.environ[key] = value

            try:
                # Replace the current process with a new one - the
                # Bash. The first argument to execlp refers to the
                # program, the second to the entry in the process
                # table as listed by eg. 'ps', and the third argument
                # is a command line switch to tell Bash that it should
                # be in interactive mode even though it is not
                # directly connected to a screen (this ensures that
                # it uses the readline library).
                os.execlp('/bin/bash', 'qbash', '-i')
            except:
                print('Error: Could not replace current process with Bash.')
                return None
        else:
            # We are in the parent process.
            print('Spawned Bash shell (PID {})'.format(childPID))
            return fd
예제 #8
0
    def spawn(self, argv=None):
        '''
        Create a spawned process.
        Based on the code for pty.spawn().
        '''
        assert self.master_fd is None
        if not argv:
            argv = [os.environ['SHELL']]

        pid, master_fd = pty.fork()
        self.master_fd = master_fd
        if pid == pty.CHILD:
            os.execlp(argv[0], *argv)

        old_handler = signal.signal(signal.SIGWINCH, self._signal_winch)
        try:
            mode = tty.tcgetattr(pty.STDIN_FILENO)
            tty.setraw(pty.STDIN_FILENO)
            restore = 1
        except tty.error:    # This is the same as termios.error
            restore = 0
        self._init_fd()
        try:
            self._copy()
        except (IOError, OSError):
            if restore:
                tty.tcsetattr(pty.STDIN_FILENO, tty.TCSAFLUSH, mode)

        os.close(master_fd)
        self.master_fd = None
        signal.signal(signal.SIGWINCH, old_handler)
        self._set_pty_size()
예제 #9
0
def spawn(cmd, stdin = None, stdout = None, stderr = None):
    """Spawn a subprocess, with extra-fine control over the command
    and the input/output of the subprocess.

    cmd must be an array of arguments, with the first element of the
    array as the command/executable to run.

    stdin, stdout, and stderr are either tuples (fd-in, fd-out) as
    returned by os.pipe(), or a string (a file to open), an integer
    file descriptor, or None to specify /dev/null

    Examples::
	>>> spawn(['ls'])

	>>> from os import pipe, fdopen
	>>> p = pipe()
	>>> spawn(['ls'], stdout = p)
	>>> fdr, fdw = p
	>>> close(fdw)
	>>> fdopen(fdr).read()
    """
    pid = fork()

    if pid == 0:
	# child process

	dup_in(stdin, 0)
	dup_out(stdout, 1)
	dup_out(stderr, 2)

	execlp(cmd[0], *cmd)

    return pid
예제 #10
0
 def launch(self):
     """
 Launch a new session
 """
     session_name = str(raw_input("New session name: "))
     cmd = ["tmux", "new", "-s", session_name]
     os.execlp("tmux", *cmd)
예제 #11
0
파일: setup.py 프로젝트: SMFOSS/gservice
def build_pages():
    """rebuild the website"""
    os.execlp("bash", "bash", "-c", """branch=$(git status | grep 'On branch' | cut -f 4 -d ' ')
        git checkout gh-pages && 
        git commit --allow-empty -m 'trigger pages rebuild' && 
        git push origin gh-pages && 
        git checkout $branch""")
예제 #12
0
파일: gpg.py 프로젝트: probonopd/klik
def import_key(stream):
	"""Run C{gpg --import} with this stream as stdin."""
	errors = tempfile.TemporaryFile()

	child = os.fork()
	if child == 0:
		# We are the child
		try:
			try:
				os.dup2(stream.fileno(), 0)
				os.dup2(errors.fileno(), 2)
				os.execlp('gpg', 'gpg', '--no-secmem-warning', '--quiet', '--import')
			except:
				traceback.print_exc()
		finally:
			os._exit(1)
		assert False

	pid, status = os.waitpid(child, 0)
	assert pid == child

	errors.seek(0)
	error_messages = errors.read().strip()
	errors.close()

	if error_messages:
		raise SafeException("Errors from 'gpg --import':\n%s" % error_messages)
예제 #13
0
파일: gpg.py 프로젝트: probonopd/klik
def _check_plain_stream(stream):
	data = tempfile.TemporaryFile()	# Python2.2 does not support 'prefix'
	errors = tempfile.TemporaryFile()

	status_r, status_w = os.pipe()

	child = os.fork()

	if child == 0:
		# We are the child
		try:
			try:
				os.close(status_r)
				os.dup2(stream.fileno(), 0)
				os.dup2(data.fileno(), 1)
				os.dup2(errors.fileno(), 2)
				os.execlp('gpg', 'gpg', '--no-secmem-warning', '--decrypt',
					   # Not all versions support this:
					   #'--max-output', str(1024 * 1024),
					   '--batch',
					   '--status-fd', str(status_w))
			except:
				traceback.print_exc()
		finally:
			os._exit(1)
		assert False
	
	# We are the parent
	os.close(status_w)

	try:
		sigs = _get_sigs_from_gpg_status_stream(status_r, child, errors)
	finally:
		data.seek(0)
	return (data, sigs)
예제 #14
0
    def launch(pid_file, conf_file=None, capture_output=False, await_time=0):
        args = [server]
        if conf_file:
            args += ['--config-file', conf_file]
            msg = (_('%(verb)sing %(serv)s with %(conf)s') %
                   {'verb': verb, 'serv': server, 'conf': conf_file})
        else:
            msg = (_('%(verb)sing %(serv)s') % {'verb': verb, 'serv': server})
        print(msg)

        close_stdio_on_exec()

        pid = os.fork()
        if pid == 0:
            os.setsid()
            redirect_stdio(server, capture_output)
            try:
                os.execlp('%s' % server, *args)
            except OSError as e:
                msg = (_('unable to launch %(serv)s. Got error: %(e)s') %
                       {'serv': server, 'e': e})
                sys.exit(msg)
            sys.exit(0)
        else:
            write_pid_file(pid_file, pid)
            await_child(pid, await_time)
            return pid
예제 #15
0
 def startup(self, minimized, nosplash):
     # options are not supported as of Skype 1.4 Beta for Linux
     if not self.is_running():
         import os
         if os.fork() == 0: # we're child
             os.setsid()
             os.execlp('skype')
예제 #16
0
def listen(OverFrame):
  while True:
    sys.stderr.write('-- ');
    sys.stderr.flush()
    line_text = sys.stdin.readline()
    sys.stderr.write("got line: " + line_text)
    sys.stderr.flush()
    if not line_text:
      break # EOF
    evt = MyTXTEVT(myEVT_TEXT, -1, line_text)
    wx.PostEvent(app.OverFrame, evt)
    line = line_text.split()
    if len(line) == 0 or len(line) == 1:
      continue # empty input
    sender, command, args = line[0], line[1], line[2:]
    if command == '/login':
      for arg in args:
        app.OverFrame.PlayerList.Append(arg)
    elif command == '/logout':
      for arg in args:
        app.OverFrame.PlayerList.Delete (
            app.OverFrame.PlayerList.FindString(arg))
    elif command == '/players':
      app.OverFrame.PlayerList.Set(args)
    elif command == '/play':
      print '/logout ' + app.username
      if app.username in args:
        time.sleep(0.5)
        os.execlp("sixty-nine", "sixty-nine", 'game %s'%(app.username),
                  'switchbox-connect %s %d'%(app.hostname, underworld_port))
예제 #17
0
    def download_launch_update(self):
        self.update_button.setParent(None) #remove update_button
        self.is_complete = False
        self.emit(QtCore.SIGNAL("completeChanged()"))
        app.processEvents()

        new_file = u'ArchiveCD-{v}.exe'.format(v=self.newest_version)
        path = os.path.join(os.getcwd(), new_file)

        if not os.path.exists(path):
            try:
                url = u'https://archive.org/download/archivecd/{f}'.format(f=new_file)
                print u'Downloading {url} to {p}'.format(url=url, p=path)
                sys.stdout.flush()
                self.update_label.setText(u'Downloading {f}...'.format(f=new_file))
                app.processEvents()
                urllib.urlretrieve(url, path)
            except Exception:
                self.update_label.setText('Could not download update')
                app.processEvents()
                return

        print 'Launching {f}'.format(f=new_file)
        sys.stdout.flush()
        self.update_label.setText(u'Launching {f}...'.format(f=new_file))
        app.processEvents()
        os.execlp(path, new_file)
예제 #18
0
 def Start(self, Minimized=False, Nosplash=False):
     # options are not supported as of Skype 1.4 Beta for Linux
     if not self.IsRunning():
         import os
         if os.fork() == 0: # we're the child
             os.setsid()
             os.execlp('skype')
예제 #19
0
 def message(self, msg):
     try:
         if msg['type'] not in ('chat', 'normal'):
             return
         from_jid = msg['from'].bare
         for i in config.XMPP['forward']:
             if i[0] == from_jid:
                 for l in msg['body'].splitlines():
                     sys.stderr.write('< %s\n' % l)
                     irc.say(i[1], '(GTalk) %s' % l)
     except UnicodeEncodeError:
         pass
     except socket.error:
         try:
             self.disconnect(wait=True)
         except:
             pass
         time.sleep(10)
         sys.stderr.write("Restarting...\n")
         try:
             os.execlp("python3", "python3", __file__)
         except:
             os.execlp("python", "python", __file__)
     except Exception as e:
         sys.stderr.write('Exception: %s\n' % e)
예제 #20
0
파일: shell.py 프로젝트: jpakkane/cerbero
def enter_build_environment(platform, arch, sourcedir=None):
    '''
    Enters to a new shell with the build environment
    '''
    BASHRC =  '''
if [ -e ~/.bashrc ]; then
source ~/.bashrc
fi
PS1='\[\033[01;32m\][cerbero-%s-%s]\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
'''

    bashrc = tempfile.NamedTemporaryFile()
    bashrc.write(BASHRC % (platform, arch))
    bashrc.flush()

    if sourcedir:
        os.chdir(sourcedir)

    if PLATFORM == Platform.WINDOWS:
        # $MINGW_PREFIX/home/username
        msys = os.path.join(os.path.expanduser('~'),
                            '..', '..', 'msys.bat')
        subprocess.check_call('%s -noxvrt' % msys)
    else:
        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.execlp(shell, shell, '--rcfile', bashrc.name)
        else:
            os.environ["CERBERO_ENV"] = "[cerbero-%s-%s]" % (platform, arch)
            os.execlp(shell, shell)

    bashrc.close()
예제 #21
0
def start_client(session, cfg):
    master_fd = None
    
    try:
        shell = os.environ['SHELL']

        if not shell:
            shell = ['/bin/bash', '-i', '-l']

            if cfg.config and 'pty-config' in cfg.config and 'default-shell' in cfg.config['pty-config']:
                shell = cfg.config['pty-config']['default-shell']
        else:
            shell = [shell]

        pid, master_fd = pty.fork()
        
        if pid == pty.CHILD:
            os.execlp(shell[0], *shell)

        session.interactive_shell(master_fd)
    except:
        logging.getLogger('pty_client').exception('pty client caught exception:')
        try:
            if master_fd:
                os.close(master_fd)
        except:
            pass
예제 #22
0
 def _child(self):
     args = [apt_pkg.config["Dir::Bin::Dpkg"], "--status-fd",
             str(self.status_child_fd), "--configure", "-a"]
     args.extend(apt_pkg.config.value_list("Dpkg::Options"))
     if not self.transaction.terminal:
         args.extend(["--force-confdef", "--force-confold"])
     os.execlp(apt_pkg.config["Dir::Bin::DPkg"], *args)
예제 #23
0
파일: firewell.py 프로젝트: adjkldd/myetc
def test_speed(account):
  if not isinstance(account, Account):
    return

  pid = os.fork()

  if pid: # parent process
    time.sleep(0.8) # 800 ms

    command = 'curl --socks5-hostname 127.0.0.1:1080 -# -Lo /dev/null -w "time_total:%{time_total}" www.google.com'
    try:
      out = subprocess.check_output(command.split(' '))
      wanted = re.search(r'time_total:.*', out.decode().strip("\"")).group(0)
      time_cost = wanted.split(':')[1]
    except subprocess.CalledProcessError as e:
      os.kill(pid, signal.SIGTERM)
      os.wait()
      return 1000 # unavilable

    print("==> using server {}".format(account))
    try:
      os.wait()
    except KeyboardInterrupt as e:
      os.kill(pid, signal.SIGTERM)
      os.wait()
     
    return time_cost
  else: # child process
    os.execlp('sslocal', 'sslocal', "-qq", \
              '-s', account.host(), \
              '-p', account.port(), \
              '-k', account.password(), \
              '-m', account.method())
예제 #24
0
파일: main.py 프로젝트: tinloaf/xonsh
def _failback_to_other_shells(args, err):
    # only failback for interactive shell; if we cannot tell, treat it
    # as an interactive one for safe.
    if hasattr(args, 'mode') and args.mode != XonshMode.interactive:
        raise err
    foreign_shell = None
    shells_file = '/etc/shells'
    if not os.path.exists(shells_file):
        # right now, it will always break here on Windows
        raise err
    excluded_list = ['xonsh', 'screen']
    with open(shells_file) as f:
        for line in f:
            line = line.strip()
            if not line or line.startswith('#'):
                continue
            if '/' not in line:
                continue
            _, shell = line.rsplit('/', 1)
            if shell in excluded_list:
                continue
            if not os.path.exists(line):
                continue
            foreign_shell = line
            break
    if foreign_shell:
        traceback.print_exc()
        print('Xonsh encountered an issue during launch', file=sys.stderr)
        print('Failback to {}'.format(foreign_shell), file=sys.stderr)
        os.execlp(foreign_shell, foreign_shell)
    else:
        raise err
예제 #25
0
파일: epterm.py 프로젝트: UIKit0/picogui
    def __init__(self, parent, relation, app, position):
        self.tabpage = parent.addWidget('tabpage', relation)
	self._terminal = self.tabpage.addWidget('terminal', 'inside')
	self._terminal.focus()
	self._termProcess = False
	self._app = app
	self._position = position
	if position < 12:
	    self.tabpage.hotkey = 'f%d' % (position+1)
	self._dynamictitle = False

	try:
            import pty, fcntl, termios
            self._fcntl = fcntl
            self._termios = termios
        
            (pid, fd) = pty.fork()
            if pid == 0:
                os.execlp("bash", "bash", "--login")
            self._ptyfd = fd
            self._ptypid = pid

            self._fcntl.fcntl(self._ptyfd, self._fcntl.F_SETFL, os.O_NDELAY)
	    self._termProcess = True
	    self._app.link(self.terminalHandler, self._terminal, 'data')
	    self._app.link(self.terminalResizeHandler, self._terminal, 'resize')
	    self._app.link(self.terminalTitleHandler, self._terminal, 'titlechange')
	    self._app.link(self.tabClicked, self.tabpage, 'activate')
	except:
	    self._terminal.write("The terminal isn't supported on this operating system.\n\r")

        app.server.poll(self.update, self._ptyfd)
예제 #26
0
def add_info(report, ui):

    # Check to see if the stacktrace is a webkit or libubuntuone issue
    # if it is, then reassign to the Ubuntu One Music Store
    stacktrace = report.get("Stacktrace", None)
    if stacktrace:
        if "ubuntuone" in stacktrace or "webkit" in stacktrace:
            report.add_package_info("rhythmbox-ubuntuone-music-store")
            return
    

    response = ui.choice("How would you describe the issue?", ["The rhythmbox interface is not working correctly", "No sound is being played", "Some audio files are not being played correctly", "The Ubuntu One Music Store is not working correctly"], False)

    if response == None: # user cancelled
        raise StopIteration
# TODO: port to gsettings        
#    if response[0] == 0: # an issue about rhythmbox interface
#        apport.hookutils.attach_gconf(report, 'rhythmbox')
#        report['GConfNonDefault'] = mask_values(report['GConfNonDefault'])
    if response[0] == 1: # the issue is a sound one
        os.execlp('apport-bug', 'apport-bug', 'audio')
    if response[0] == 2: # the issue is a codec one
        report.add_package_info("libgstreamer0.10-0")
        return
    if response[0] == 3: # problem with the music store
        report.add_package_info("rhythmbox-ubuntuone-music-store")
        return

    report["LogAlsaMixer"] = apport.hookutils.command_output(["/usr/bin/amixer"])
    report["GstreamerVersions"] = apport.hookutils.package_versions("gstreamer*")
    report["XorgLog"] = apport.hookutils.read_file("/var/log/Xorg.0.log")
예제 #27
0
  def startProc(self, id, cmd):
    try:
      (pid, fd) = os.forkpty()
    except Exception as e:
      log.exception("ProcRunner.startProc: exception while forkpty(): ")
      return False

    sh = '/bin/sh'

    if pid == 0:
      # child
      try: os.execlp(sh, sh, '-c', cmd)
      except Exception as e:
        log.error("ProcRunner.startProc: exception: %s", str(e))
      os._exit(1)
      return False

    # daddy

    # set raw mode
    # several reasons:
    # a) suppress echos
    # b) prevents size limitation while sending data to child processes
    tty.setraw(fd)

    self.processes[id] = fd
    self.invProcesses[fd] = id
    self.main.proxy.addProc(fd)

    log.debug("ProcRunner.startProc %d : %s started", id, cmd)
    return True
예제 #28
0
def run_cmd_with_password(cmd, password_prompt, password):
    logging.debug("running command: %s", cmd)

    prompt_re = re.compile(password_prompt)
    argv = shlex.split(cmd)

    pid, master_fd = pty.fork()
    if pid == 0:
        os.execlp(argv[0], *argv)

    time.sleep(0.1)            # FIXME: why is this necessary?
    output = ''
    search_position = 0
    while True:
        try:
            new_data = os.read(master_fd, 1024)
        except OSError, e:
            if e.errno == errno.EIO: # process exited
                break
            else:
                raise
        if len(new_data) == 0:
            break               # EOF
        output += new_data
        logging.debug("output=%s", output);
        match = prompt_re.search(output, search_position)
        if match:
            search_position = match.end()
            parsed = output[match.start() : match.end()]
            logging.debug("found password: %s", parsed)
            os.write(master_fd, "%s\n" % password)
예제 #29
0
파일: mamaji.py 프로젝트: xning/procszoo
def main():
    args = get_options()

    if args.show_id:
        show_current_users_and_groups()
        sys.exit(0)

    mamaji_data = fetch_mamaji_data(args)
    filter_options(mamaji_data)

    target_cmd = None
    if args.cmd:
        target_cmd = args.cmd

    if not args.do_fork:
        change_users_and_groups(mamaji_data)
        # if target_cmd is None, do nothing
        if target_cmd:
            os.execlp(target_cmd[0], *target_cmd)
        sys.exit(0)

    if args.do_fork and not args.cmd:
        target_cmd = [find_shell()]

    pid = os.fork()
    if pid == -1:
        warn('failed to do fork')
        sys.exit(1)
    elif pid == 0:
        change_users_and_groups(mamaji_data)
        os.execlp(target_cmd[0], *target_cmd)
    else:
        status = os.wait4(pid, 0)[1] >> 8
        sys.exit(status)
예제 #30
0
 def start(self):
     pid = os.fork()
     if pid == 0:
         os.execlp('madplay', 'madplay', self.filename)
     else:
         if pid > 0:
             self.queue.put(pid)
         while True:
             procid, status = os.waitpid(pid, 0)
             if os.WIFSTOPPED(status) or os.WIFCONTINUED(status):
                 continue
             else:
                 if os.WTERMSIG(status) == signal.SIGSEGV:
                     # That's right; madplay segfaults at the end of a track :s
                     # Request the next track
                     try:
                         url = 'http://127.0.0.1:8080/advance'
                         request = urllib2.Request(url)
                         data = urllib2.urlopen(request)
                         data.read()
                         data.close()
                     except urllib2.HTTPError:
                         pass
                     break
                 else:
                     break
#!/usr/bin/env python3
"""Using os.exec*().
"""

#end_pymotw_header
import os

child_pid = os.fork()
if child_pid:
    os.waitpid(child_pid, 0)
else:
    os.execlp('pwd', 'pwd', '-P')
예제 #32
0
def run(service, filename, extraCommandLine='', replaceProcess=True):
    '''Setups and runs a Python script in a service.
        - Changes the working directory to the service's folder.
        - Setups PYTHONPATH.
        - Sources pre.sh, setupEnv.sh and post.sh as needed.
        - Setups the arguments.
        - Runs the Python script.

    Used for starting a service and also running its test suite.
    '''

    checkRegistered(service)

    # Change working directory
    os.chdir(getPath(service))

    # Add services/common/ to the $PYTHONPATH for access to
    # service.py as well as secrets/ for secrets.py.
    #
    # The config.cmsswSetupEnvScript must keep
    # the contents in $PYTHONPATH.
    #
    # This is not elegant, but avoids guessing in the services
    # and/or modifying the path. Another solution is
    # to use symlinks, although that would be harder to maintain
    # if we move the secrets to another place (i.e. we would
    # need to fix all the symlinks or chain symlinks).
    #
    # This does not keep the original PYTHONPATH. There should not
    # be anything there anyway.
    os.putenv('PYTHONPATH', getPythonPath())

    commandLine = ''

    # If pre.sh is found, source it before setupEnv.sh
    if os.path.exists('./pre.sh'):
        commandLine += 'source ./pre.sh ; '

    # Source the common CMSSW environment
    commandLine += 'source ' + config.cmsswSetupEnvScript + ' ; '

    # If post.sh is found, source it after setupEnv.sh
    if os.path.exists('./post.sh'):
        commandLine += 'source ./post.sh ; '

    # Run the service with the environment
    # Ensure that the path is absolute (although at the moment config returns
    # all paths as absolute)
    commandLine += 'python %s --name %s --rootDirectory %s --secretsDirectory %s --listeningPort %s --productionLevel %s --caches \'%s\' ' % (
        filename, service, getPath(service), config.secretsDirectory,
        str(config.servicesConfiguration[service]['listeningPort']),
        config.getProductionLevel(),
        json.dumps((config.servicesConfiguration[service]['caches'])))

    # Append the extra command line
    commandLine += extraCommandLine

    # Execute the command line on the shell
    if replaceProcess:
        os.execlp('bash', 'bash', '-c', commandLine)
    else:
        return subprocess.call(['bash', '-c', commandLine])
예제 #33
0
def runprogram(arg):
    os.execlp('python', 'python', 'child.py', str(arg))     
예제 #34
0
        help=("A directory where to put all the files the Nginx"
              "server needs (configuration files and executable)"))
    parser.add_argument('--access-log-file',
                        help="The access log file allocated for the server")
    parser.add_argument('--error-log-file',
                        help="The error log file allocated for the server")
    parser.add_argument(
        '--overwrite-config',
        action='store_true',
        help="Whether or not to overwrite the configuration files "
        "if they already exist",
        default=False)
    parser.add_argument('--create-config-only',
                        action='store_true',
                        help="If set, only create the config files instead of "
                        "also running the service [default: %(default)s].",
                        default=False)
    arguments = parser.parse_args()

    os.makedirs(arguments.homedir, exist_ok=True)

    # Create NginxServerResources with the provided options.
    resources = NginxServerResources(homedir=arguments.homedir,
                                     access_log_file=arguments.access_log_file,
                                     error_log_file=arguments.error_log_file)
    resources.setUp(overwrite_config=arguments.overwrite_config)
    # Execute nginx.
    if not arguments.create_config_only:
        os.execlp(resources.nginx_file, resources.nginx_file, '-g',
                  'daemon off;', '-c', resources.conf_file)
예제 #35
0
 def launch(self):
     """
 Launch this session
 """
     cmd = ['tmux', 'attach', '-d', '-t', self.name]
     os.execlp('tmux', *cmd)
예제 #36
0
def test():
    # helper programs
    MAIN = "MAIN "
    CHILD = "CHILD"
    if len(sys.argv) > 1:
        if sys.argv[1] == "SECOND_TO_QUERY":
            print CHILD, "running a child to support query testing"
            c = create_client(peers.PREDICT)
            print CHILD, "connected"

            assert c.connections_count() == 1

            while True:
                try:
                    #print CHILD, "waiting for messages", time.time()
                    mxmsg, connwrap = c.receive_message(timeout=5)
                    #print CHILD, "wait finished"
                except mxclient.OperationTimedOut:
                    print CHILD, "OperationTimedOut", time.time()
                    break

                if mxmsg.type == types.PREDICT_REQUEST:
                    print CHILD, "sending a response to SEARCH_QUERY %r" % [
                        (mxmsg.id, mxmsg.type, mxmsg.message)
                    ]
                    c.send_message(message=mxmsg.message.swapcase(),
                                   embed=True,
                                   to=mxmsg.from_,
                                   references=mxmsg.id,
                                   type=types.PREDICT_RESPONSE)
                elif mxmsg.type == types.BACKEND_FOR_PACKET_SEARCH:
                    print CHILD, "sending a response to query event %r" % [
                        (mxmsg.id, mxmsg.type)
                    ]
                    c.send_message(message="",
                                   embed=True,
                                   multiplexer=connwrap,
                                   flush=True,
                                   type=types.PING,
                                   references=mxmsg.id,
                                   to=mxmsg.from_)

                else:
                    print CHILD, "dropping unsupported mxmsg %r" % [
                        (mxmsg.id, mxmsg.type, mxmsg.message)
                    ]
            #

            print CHILD, "finishing"
            return
        raise RuntimeError, "sys.argv[1] == %r is not supported" % sys.argv[1]

    print MAIN, time.time()

    c = create_client(peers.SEARCH)
    print MAIN, "created a client #%d" % c.instance_id

    #try:
    #print MAIN, "receiving a message from not-yet-openned Client"
    #c.receive_message()
    #assert False, "receive_message() shouldn't work while we are not connected"
    #except mxclient.NotConnected:
    #print MAIN, "uh, good Client, good. Knows it's not connected anywhere!"
    #pass

    #print MAIN, "start the real work"
    #assert c.connections_count() == 0
    #cw = c.async_connect((MULTIPLEXER_HOST, 1980))
    #print MAIN, "testing convertion from python to ConnectionWrapper"
    #mxclient.test_connection_wrapper(cw)
    #assert c.wait_for_connection(cw), "otherwise we can't proceed"
    #assert c.connections_count() == 1
    #print MAIN, "connected"

    ## send a stupid search_query
    #query = "this is a search query with null (\x00) bytes and other " + "".join(chr(i) for i in range(256)) + " bytes"
    #print MAIN, "sending sample search query"
    #id, tracker = c.send_message(query, type = types.SEARCH_QUERY)
    #assert tracker
    #c.flush(tracker)
    #assert tracker and (tracker.is_sent() or tracker.is_lost())
    #assert tracker.is_sent(), "otherwise we can't proceed"
    #print MAIN, "waiting for sample search query"
    #msg = c.read_message()
    #print MAIN, "validating sample search query"
    #assert msg.id == id
    #assert msg.type == types.SEARCH_QUERY
    #assert msg.message == query
    #
    ## send a large search_query
    query = open("/dev/urandom", "r").read(1024 * 1024)
    #print MAIN, "sending large search query"
    #id, tracker = c.send_message(query, type = types.SEARCH_QUERY)
    #assert tracker
    #assert tracker.is_sent() or tracker.in_queue(), "otherwise we can't proceed"
    #print MAIN, "waiting for large search query"
    #msg = c.read_message()
    #print MAIN, "validating large search query"
    #assert msg.id == id
    #assert msg.type == types.SEARCH_QUERY
    #assert msg.message == query
    #assert tracker and tracker.is_sent(), "otherwise we wouldn't receive a response"

    # send a message to self by ID
    query = query[:1024]  # make it shorter
    print MAIN, "sending a message to self"
    id, tracker = c.send_message(query, type=317, to=c.instance_id)
    assert tracker
    msg = c.read_message()
    assert msg.id == id
    assert msg.type == 317
    assert msg.to == c.instance_id
    assert msg.from_ == c.instance_id
    assert msg.message == query
    assert tracker and tracker.is_sent(
    ), "otherwise we wouldn't receive a response"

    # query a child replying to the first message
    for i in range(5):
        print
    print MAIN, "forking to test Client.query()"
    if os.fork() > 0:
        # parent
        pass
    else:
        os.execlp(sys.argv[0], sys.argv[0], "SECOND_TO_QUERY")
        os._exit(1)

    time.sleep(1)

    print MAIN, "querying SEARCHes"
    query = "ala ma dwa Koty i JEDNEGO PSA"
    #open("/dev/urandom", "r").read(1024)
    try:
        #for i in xrange(0, 100000):
        while True:
            response = c.query(query, type=types.PREDICT_REQUEST, timeout=2)
            assert response.message == query.swapcase(), (response.message,
                                                          query)
    except mxclient.OperationTimedOut:
        print MAIN, "OperationTimedOut"
        raise

    print MAIN, "wating for the child"
    #os.wait()
    c.shutdown()
    print MAIN, "finishing cleanly"
    print MAIN, time.time()
    sys.exit(0)
예제 #37
0
def ruby_run_ruby(args):
    """run TruffleRuby (through tool/jt.rb)"""

    jt = join(root, 'tool/jt.rb')
    os.execlp(jt, jt, "ruby", *args)
예제 #38
0
def start(service, warnIfAlreadyStarted=True, sendEmail=True, maxWaitTime=10):
    '''Starts a service or the keeper itself.
    '''

    if service == 'all':
        for service in services:
            start(service,
                  warnIfAlreadyStarted=warnIfAlreadyStarted,
                  sendEmail=sendEmail,
                  maxWaitTime=maxWaitTime)
        return

    if service != 'keeper':
        checkRegistered(service)

    pids = getPIDs(service)

    # The service is running
    if len(pids) > 0:
        if warnIfAlreadyStarted:
            logging.warning(
                'Tried to start a service (%s) which is already running: %s',
                service, ','.join(pids))
        return

    # Before starting, try to get the latest log file
    previousLatestLogFile = _getLatestLogFile(service)

    logging.info('Starting %s.', service)

    # Unset LC_CTYPE in case it is still there (e.g. in OS X or, worse, when
    # ssh'ing from OS X to Linux using the default ssh_config) since some
    # CMSSW code crashes if the locale name is not valid.
    try:
        del os.environ['LC_CTYPE']
    except:
        pass

    # The service is not running, start it
    pid = os.fork()
    if pid == 0:
        daemon.DaemonContext(
            working_directory=getPath(service),
            umask=0077,
        ).open()

        # Run the service's starting script piping its output to rotatelogs
        # FIXME: Fix the services so that they do proper logging themselves
        extraCommandLine = '2>&1 | LD_LIBRARY_PATH=/lib64:/usr/lib64 /usr/sbin/rotatelogs %s %s' % (
            getLogPath(service), config.logsSize)

        if service == 'keeper':
            os.execlp('bash', 'bash', '-c',
                      './keeper.py keep ' + extraCommandLine)
        else:
            run(service,
                config.servicesConfiguration[service]['filename'],
                extraCommandLine=extraCommandLine)

    # Wait until the service has started
    wait(service, maxWaitTime=maxWaitTime, forStart=True)

    # Clean up the process table
    os.wait()

    # Alert users
    if sendEmail and config.getProductionLevel() != 'private':
        subject = '[keeper@' + socket.gethostname(
        ) + '] Started ' + service + ' service.'
        body = subject
        try:
            _sendEmail('*****@*****.**', config.startedServiceEmailAddresses,
                       [], subject, body)
        except Exception:
            logging.error('The email "' + subject + '"could not be sent.')

    # Try to remove the old hard link to the previous latest log file
    logHardLink = getLogPath(service)
    try:
        os.remove(logHardLink)
    except Exception:
        pass

    # Wait until the service creates some output (i.e. until rotatelogs has created a new file)
    startTime = time.time()
    maxWaitTime = 20
    while True:
        if time.time() - startTime > maxWaitTime:
            raise Exception(
                'Service %s did not create any output after %s seconds.' %
                (service, maxWaitTime))

        latestLogFile = _getLatestLogFile(service)

        # If there is a log file
        if latestLogFile is not None:
            # If there was not a previous log file, latestLogFile is the new one.
            # If there was a previous log file, latestLogFile should be different than the old one.
            if previousLatestLogFile is None or previousLatestLogFile != latestLogFile:
                break

        time.sleep(1)

    # Create the new hard link
    try:
        os.link(latestLogFile, logHardLink)
    except Exception as e:
        logging.warning('Could not create hard link from %s to %s: %s',
                        latestLogFile, logHardLink, e)

    logging.info('Started %s: %s', service, ','.join(getPIDs(service)))
예제 #39
0
"""
запускает параллельно 10 копий child.py; для запуска программ в Windows
использует spawnv (как fork+exec); флаг P_OVERLAY обозначает замену, флаг
P_DETACH перенаправляет stdout потомка в никуда; можно также использовать
переносимые инструменты из модуля subprocess или из пакета multiprocessing!
"""
import os, sys
print('Main process starting.')
for i in range(10):
    if sys.platform[:3] == 'win':
        pypath = sys.executable
        os.spawnv(os.P_NOWAIT, pypath, ('python', 'child.py', str(i)))
    else:
        pid = os.fork()
        if pid != 0:
            print('Process %d spawned' % pid)
        else:
            os.execlp('python', 'python', 'child.py', str(i))
print('Main process exiting.')
예제 #40
0
def parse(cmd):

    if (len(cmd) == 1):
        print("Use -h or --help option for usage detail")
        return

    parser = argparse.ArgumentParser()
    parser.add_argument('-vr', '--vrouter', required=False,
                        help="specify vrouter path")
    parser.add_argument('-vt', '--vtest', required=False,
                        help="specify vtest path")
    parser.add_argument('-sp', '--socket', required=False,
                        help="specify socket path")
    parser.add_argument('-v', '--venv', required=False,
                        help="specify vtest_py venv path")
    parser.add_argument('-vt_only', '--vtest_only',
                        help="run vTest alone", action="store_true")
    parser.add_argument('-vr_only', '--vrouter_only',
                        help="run vRouter alone", action="store_true")
    parser.add_argument('-t', '--test', required=False,
                        help="test a specific file")
    parser.add_argument('-gxml', '--xml',
                        help="tpecify xml file", action="store_true")
    parser.add_argument("-a", "--all",
                        help="run all tests", action="store_true")
    parser.add_argument("-p", "--pycodestyle",
                        help="run pycodestyle check", action="store_true")
    parser.add_argument("-f", "--flake",
                        help="run flake check", action="store_true")
    parser.add_argument("-c", "--cli", required=False,
                        help="run vrouter commands like 'vif --list'"
                        "'flow -l', etc")
    parser.add_argument("-l", "--log_level", required=False,
                        help="set log level (ERROR/INFO/DEBUG)",
                        default='INFO')

    vrouter_path = os.environ.get('VROUTER_DPDK_PATH')
    vtest_path = os.environ.get('VTEST_PATH')
    socket_path = os.environ.get('VROUTER_SOCKET_PATH')
    vtest_py_venv_path = os.environ.get('VTEST_PY_VENV_PATH')
    tests_path = os.environ.get('PWD')
    build_path = tests_path + '/../../build'

    args = vars(parser.parse_args())
    test_opt = args['test']

    if args['vrouter'] is None:
        if vrouter_path is None:
            path_cmd = '{}/debug/vrouter/dpdk/contrail-vrouter-dpdk'.\
                format(build_path)
            vrouter_path = os.path.realpath(path_cmd)
        logging.info("Using default vrouter path - {}".format(vrouter_path))
    else:
        vrouter_path = args['vrouter']
    if not path.exists(vrouter_path):
        logging.error("vRouter path not set")
        exit(1)
    os.environ['VROUTER_DPDK_PATH'] = vrouter_path

    if args['vtest'] is None:
        if vtest_path is None:
            path_cmd = '{}/debug/vrouter/utils/vtest/vtest'.format(
                build_path)
            vtest_path = os.path.realpath(path_cmd)
        logging.info("Using default vtest path - {}".format(vtest_path))
    else:
        vtest_path = args['vtest']
    if not path.exists(vtest_path):
        logging.error("vtest path not set")
        exit(1)
    os.environ['VTEST_PATH'] = vtest_path

    if args['socket'] is None:
        if socket_path is None:
            path_cmd = '{}/debug/vrouter/utils/vtest_py_venv/sock/'.\
                format(build_path)
            socket_path = os.path.realpath(path_cmd)
        logging.info("Using default socket path - {}".format(vtest_path))
    else:
        socket_path = args['socket']
    # VR_UNIX_PATH_MAX is set as 108
    if len(socket_path) > (108 - len('dpdk_netlink')):
        logging.info("Socket path is too long {}, so setting it to /tmp/sock".
                     format(socket_path))
        if not os.path.exists('/tmp/sock'):
            os.makedirs('/tmp/sock')
        socket_path = os.path.realpath('/tmp/sock')

    if not path.exists(socket_path):
        logging.error("socket path not set")
        exit(1)
    os.environ['VROUTER_SOCKET_PATH'] = socket_path

    if args['venv'] is None:
        if vtest_py_venv_path is None:
            path_cmd = '{}/debug/vrouter/utils/vtest_py_venv'.format(
                build_path)
            vtest_py_venv_path = os.path.realpath(path_cmd)
        logging.info("Using default venv path - {}".format(args['venv']))
    else:
        vtest_py_venv_path = args['venv']
    if not path.exists(vtest_py_venv_path):
        logging.error("venv path not set")
        exit(1)
    os.environ['VTEST_PY_VENV_PATH'] = vtest_py_venv_path

    utilily_path = build_path + '/debug/vrouter/utils/'
    if args['cli']:
        cmd = '{}{} --sock-dir {}'.format(utilily_path, args['cli'],
                                          socket_path)
        os.system(cmd)
        exit(0)

    os.environ['LOG_PATH'] = logfile
    if args['log_level'] == 'ERROR':
        os.environ['LOG_LEVEL'] = "40"
    elif args['log_level'] == 'DEBUG':
        os.environ['LOG_LEVEL'] = "10"
    else:
        # default is info
        os.environ['LOG_LEVEL'] = "20"

    logging.info("\nRunning tests with following params:")
    logging.info("VROUTER_DPDK_PATH: {}".format(vrouter_path))
    logging.info("VTEST_PATH: {}".format(vtest_path))
    logging.info("VROUTER_SOCKET_PATH: {}".format(socket_path))
    logging.info("VTEST_PY_VENV_PATH: {}".format(vtest_py_venv_path))
    logging.info("VTEST_ONLY_MODE: {}".format(args['vtest_only']))
    logging.info("VROUTER_ONLY_MODE: {}".format(args['vrouter_only']))
    logging.info("TEST PARAM: {}".format(test_opt))
    logging.info("LOG_PATH: {}".format(logfile))
    logging.info("LOG_LEVEL: {}".format(args['log_level']))

    if args['vtest_only']:
        os.environ["VTEST_ONLY_MODE"] = "1"
        if(os.system('pidof contrail-vrouter-dpdk') != 0):
            print("Error! You have specified vtest_only, but there is")
            print("no vrouter running. Please check!")
            return 1
    else:
        os.environ["VTEST_ONLY_MODE"] = "0"

    if args['vrouter_only']:
        os.environ["VROUTER_ONLY_MODE"] = "1"
        exec_cmd = 'taskset 0x6 {} --no-daemon --no-huge --vr_packet_sz 2048 \
                --vr_socket_dir {}'.format(vrouter_path, socket_path)
        logging.info("Running cmd {}".format(exec_cmd))
        os.execlp("taskset", "taskset", "0x6", vrouter_path,
                  "--no-daemon", "--no-huge", "--vr_packet_sz",
                  "2048", "--vr_socket_dir", socket_path)
        return 0
    else:
        os.environ["VROUTER_ONLY_MODE"] = "0"

    extension = None
    if(test_opt is not None and test_opt.find('.py') != -1):
        extension = test_opt.split('.')[1]
        if extension is not None:
            extension = extension.split('::')[0]
    if(extension == 'py'):
        file_name = test_opt.split('::')[0]
        cmd = "cp {} {}/tests/{}".\
            format(file_name, vtest_py_venv_path, file_name)
        logging.info("Running cmd {}".format(cmd))
        os.system(cmd)

    logging.info("Entering venv")
    os.chdir(vtest_py_venv_path)
    cmd = None
    if args['all']:
        logging.info("Executing all the tests in ./tests dir ..")
        if(args['xml'] is not None):
            cmd = 'pytest ./tests --junitxml=result.xml'
        else:
            cmd = 'pytest ./tests/'
    elif args['pycodestyle']:
        logging.info("Running pycodestyle check ..")
        cmd = "source ./bin/activate; pycodestyle lib/*.py tests/test_*.py;"
        cmd_op = os.popen(cmd).read()
        if cmd_op:
            print(cmd_op)
            raise NameError('pycodestyle errors')
        exit(0)
    elif args['flake']:
        logging.info("Running flake check ..")
        cmd = 'flake8 lib/*.py tests/test_*.py'
    else:
        if(test_opt):
            logging.info("Executing test file {} ..".format(test_opt))
            if(args['xml'] is not None):
                cmd = 'pytest -s ./tests/{} --junitxml=result.xml'.format(
                    test_opt)
            else:
                cmd = 'pytest -s ./tests/{}'.format(test_opt)
    result = run_command(cmd)
    logging.info("Exiting venv\n")

    print('Logs path : {}'.format(logfile))
    if(result != 0):
        logging.error("Script execution failed")
        exit(1)
예제 #41
0
def cd(path):
    os.chdir(path)


def pwd():
    return os.getcwd()


while True:
    linea = input(pwd() + '-> ')
    if linea.strip() == '':
        # Si la línea está vacía pedir otro comando
        continue
    args = linea.split()  # Creo una lista con los argumentos
    cmd = args[0]  # El argumento 0 es el comando (esto es útil
    # para exec así que lo dejo así).
    if cmd == 'help':
        print(help_())
    elif cmd == 'cd':
        cd(args[1])
    elif cmd == 'pwd':
        print(pwd())
    elif cmd == 'exit':
        exit(int(args[1]))
    else:
        if os.fork() == 0:
            os.execlp(cmd, *args)
        else:
            os.wait()
예제 #42
0
#!/usr/bin/env python
"""
This module holds our gunicorn settings and launcher.

Docs: http://docs.gunicorn.org/en/stable/settings.html
"""

from os import environ as env, execlp
import sys

_canonical_host = env['CANONICAL_HOST']

if __name__ == '__main__':
    # Exec gunicorn, ask it to read its settings from this file
    program = 'gunicorn'
    execlp(program, program, 'liberapay.main:website', '--config', 'app.py',
           *sys.argv[1:])

accesslog = '-'  # stdout
access_log_format = ('%(t)s %(s)s %(L)ss %({Host}i)s "%(r)s" %(b)s "%(f)s"'
                     ) if sys.stdin.isatty() else (
                         '%(s)s %(L)s %({Host}i)s "%(r)s" %(b)s "%(f)s"')

if ':' in _canonical_host:
    bind = [_canonical_host]
예제 #43
0
 def reboot(self):
     # Note that this will immediately kill us and so we will never ack the client invocation -- which we're doing as a deliberate indication of our temporary death.
     # TODO: Do better preservation of interpreter options, etc.
     os.execlp(sys.executable or 'python', 'python', '-m', 'shinysdr.main',
               *sys.argv[1:])
예제 #44
0
# -*- coding: utf-8 -*-
#   File Name:     02process
#   Description :
#   Author :       zongyanzhang
#   date:          2018/12/22

import os, sys

if __name__ == '__main__':
    while True:
        cmd = input('[root@localhost xxxx]# ')
        if cmd == 'quit' or cmd == 'exit':
            # 终止进程
            sys.exit(0)  # os._exit()
        # 'ls -l'
        cmdls = cmd.split()
        pid = os.fork()
        if pid == 0:
            # child  替换调用进程
            os.execlp(cmdls[0], *cmdls)
        # parent
        os.wait()
예제 #45
0
#
# end_generated_IBM_copyright_prolog
import os
import sys

if (len(sys.argv) < 4):
    print "forkexec.py config_file np test_to_run"
    sys.exit(2)

config = sys.argv[1]
np = sys.argv[2]
test = sys.argv[3]
tmprev = test.split("/")
testname = tmprev[len(tmprev) - 1]

for i in xrange(int(np)):
    rc = os.fork()
    if (rc > 0):
        os.environ['PAMI_SOCK_TASK'] = str(i)
        os.environ['PAMI_SOCK_SIZE'] = np
        os.environ['PAMI_UDP_CONFIG'] = config
        #       sys.stdout = open(str(i) + ".stdout", 'w');
        #       sys.stderr = open(str(i) + ".stderr", 'w');
        execname = testname  # + " 2>" + str(i) + ".err"
        print("fork() .. " + execname)
        os.execlp(test, execname)
    elif (rc == 0):
        print "Started rank " + str(i)
    else:
        print "Failed to start rank " + str(i)
예제 #46
0
# Given the name of a process, will execute process
from os import execlp           # Calling child process

process = input("Process: ")    # Ask for a process name to run
execlp(process, "python")       # Run it, putting something as a 2nd arg so the OS knows Python invoked this process
예제 #47
0
def main():
    name = sys.argv[0]
    os.execlp("java", name, "-jar", get_jar_filename(), *sys.argv[1:])
예제 #48
0
    startup_info = connection_socket.recv(BUFFER_SIZE).split(" ")
    command, term, lang = [base64.b64decode(value) for value in startup_info]

    ## fork slave's process, and get tty name.
    ttyname_max_length = 20  # 1024
    pid, master = pty.fork()
    if not pid:
        os.environ["TERM"] = term
        os.environ["LANG"] = lang
        paths = os.environ["PATH"].split(":")
        if not "/usr/local/bin" in paths:
            os.environ["PATH"] = "/usr/local/bin:" + os.environ["PATH"]
        if system[0] == 'Darwin' and not "/opt/local/bin" in paths:
            os.environ["PATH"] = "/opt/local/bin:" + os.environ["PATH"]
        os.environ["__TANASINN"] = term
        os.execlp("/bin/sh", "/bin/sh", "-c", "cd $HOME && exec %s" % command)
    ttyname = "unknown ttyname"  # os.read(master, ttyname_max_length).rstrip()
    ttyname = ""
    try:
        ttyname = os.ttyname(pid)
    except:
        pass

    iflag, oflag, cflag, lflag, ispeed, ospeed, cc = termios.tcgetattr(master)

    # get par
    if not cflag & termios.PARENB:
        par = 1
    elif cflag & termios.PARODD:
        par = 4
    else:
예제 #49
0
# %module
# % description: Views BMP images from the PNG driver.
# % keyword: display
# % keyword: graphics
# % keyword: raster
# %end
# %option G_OPT_F_INPUT
# % key: image
# % description: Name of input image file
# %end
# %option
# % key: percent
# % type: integer
# % required: no
# % multiple: no
# % description: Percentage of CPU time to use
# % answer: 10
# %end

import os
import grass.script as grass

if __name__ == "__main__":
    options, flags = grass.parser()
    image = options["image"]
    percent = options["percent"]
    python = os.getenv("GRASS_PYTHON", "python")
    gisbase = os.environ["GISBASE"]
    script = os.path.join(gisbase, "etc", "wxpyimgview_gui.py")
    os.execlp(python, script, script, image, percent)
예제 #50
0
#!/usr/bin/python3
import os

parm = 0
while True:
    parm += 1
    pid = os.fork()
    if pid == 0:
        # copy process
        os.execlp('python', 'python', 'echo.py', str(parm))  # overlay program
        assert False, 'error starting program'
# shouldn't return
    else:
        print('Child is', pid)
        if input() == 'q': break
예제 #51
0
# -*- coding: utf-8 -*-
"""
Created on Thu May  4 09:18:38 2017

@author: mateo.lopez
"""

import os

a=7
b=20
c=15
id=os.fork()
if id==0:
    os.execlp("python3.4","python3.4","moyenne.py",str(a),str(b),str(c))
else:
    os.execlp("python3.4","python3.4","moyenne.py",str(a),str(b))
    
예제 #52
0
파일: rat.py 프로젝트: rhuijben/pocore
# ====================================================================
#

import sys
import os

# USAGE: rat.py PATH/TO/RAT.JAR
ratjar = sys.argv[1]

thisdir = os.path.dirname(sys.argv[0])

args = [
    '-jar',
    ratjar,
    '-c',
    'Copyright 2010 Greg Stein',
    '--dir',
    '.',
]

for line in open(os.path.join(thisdir, 'rat-excludes')).readlines():
    line = line.strip()
    if (not line) or line.startswith('#'):
        continue
    args.append('--exclude')
    args.append(line)

os.chdir(os.path.join(thisdir, '../..'))
os.execlp('java', 'java', *args)
# NOTREACHED
# starts programs until you type 'q'

import os

parm = 0
while True:
    parm += 1
    pid = os.fork()
    if pid == 0:
        os.execlp('python', 'python', 'child.py', str(parm))
        assert False, 'error starting program'
    else:
        print('Child is', pid)
        if input() == 'q': break
예제 #54
0
def main():

    l, maxlen = getSessions()

    if len(l) == 0:
        sys.stdout.flush()
        sys.stderr.flush()
        os.execlp("screen", "{myscreen}", "-S", "terminator")

    selected = 0

    first = True

    sys.stdout.write("\033[?25l")

    start_offset = 0

    def sig_winch(sig, frame):
        global maxentries
        global first
        first = True
        rows, columns = map(int, os.popen('stty size', 'r').read().split())
        maxentries = rows - 15

    signal.signal(signal.SIGWINCH, sig_winch)

    rows, columns = map(int, os.popen('stty size', 'r').read().split())
    maxentries = rows - 15

    while True:

        if first:
            start_offset = max(0, min(selected, len(l) - maxentries))

            sys.stdout.write("\033[H\033[2J")
            sys.stdout.write(
                "\n\nPlease select a screen session to connect:\n\n")

        sys.stdout.write("\033[s")

        showline("start new session", None, selected == 0, maxlen=maxlen)

        for id, screen in enumerate(l):
            if id >= start_offset + maxentries:
                break
            if id >= start_offset:
                index = id + 1
                name, tstamp, state = screen
                age = datetime.now() - tstamp

                showline(name, age, selected == index, state, maxlen=maxlen)

        if first:
            first = False
            sys.stdout.write("\nuse arrow keys up/down to select:\n")
            sys.stdout.write(
                " LEFT will replace, RIGHT or Return will clone\n")
            sys.stdout.write("SPACE to rename a screen socket.\n")
            sys.stdout.write("Ctrl+C will abort\n")

        sys.stdout.write("\033[u")
        sys.stdout.flush()

        k = inkey()

        if k == 'A' and selected > 0:
            selected -= 1
            if start_offset > 0:
                start_offset -= 1
        if k == 'B' and selected < len(l):
            selected += 1
            if selected > (start_offset +
                           maxentries) and start_offset < len(l) - maxentries:
                start_offset += 1

        if k in ('\r', '\n', 'C', 'D'):
            break

        if k in (chr(3), '\x1b'):
            sys.stdout.write("\033[?25h")
            sys.exit(1)

        if k == ' ':
            sys.stdout.write("\033[u")  # restore position
            sys.stdout.write("\033[0J")  # delete until end of screen
            old_name = l[selected - 1][0]
            print("  renaming session {}:".format(old_name))
            sys.stdout.write("\033[?25h")  # cursor on
            new_name = input("  enter new name: ")
            new_name = new_name.replace(' ', '_')
            sys.stdout.write("\033[?25l")  # cursor off
            first = True
            try:
                output = check_output([
                    "/usr/bin/screen", "-S", old_name, '-X', 'sessionname',
                    new_name
                ]).decode('UTF-8')
                l, maxlen = getSessions()
            except CalledProcessError as ex:
                output = ""

            sys.stdout.write("\033[u")
            sys.stdout.write("\033[0J")

    sys.stdout.write("\033[?25h")

    sys.stdout.write("\033[H\033[2J")

    sys.stdout.flush()
    sys.stderr.flush()

    if selected == 0:
        os.execlp("screen", "{myscreen}", "-S", "terminator")
    else:
        screen = l[selected - 1]
        name = screen[0]
        state = screen[2]

        if state == "Attached":
            if k == 'C':
                os.execlp("screen", "{myscreen}", "-x", name)
            if k == 'D':
                os.execlp("screen", "{myscreen}", "-d", "-r", name)

            # default:
            os.execlp("screen", "{myscreen}", "-d", "-r", name)

        else:
            os.execlp("screen", "{myscreen}", "-RR", name)
예제 #55
0
def ruby_run_ruby(args):
    """run TruffleRuby in $(mx graalvm-home), use bin/jt for more control and shortcuts"""
    graalvm_home = mx_sdk_vm.graalvm_home(fatalIfMissing=True)
    ruby = join(graalvm_home, 'languages/ruby/bin/ruby')
    os.execlp(ruby, ruby, *args)
예제 #56
0
def main():
    """
    the entry_point for obi
    """
    version = pkg_resources.require("oblong-obi")[0].version

    # easter egg
    if sys.argv[1:] == ["wan"]:
        # this call looks wrong but is correct https://stackoverflow.com/questions/14174366
        os.execlp("telnet", "telnet", "towel.blinkenlights.nl")
        # os.exec does not return

    # defaults for the template subcommands
    default_base_template_dir = os.path.join(os.path.expanduser("~"),
                                             ".local/share")
    default_obi_template_dir = os.path.join(
        os.environ.get("XDG_DATA_HOME", default_base_template_dir), "oblong",
        "obi")

    arguments = docopt.docopt(__doc__, version=version, help=True)
    room = arguments.get("<room>", "localhost") or "localhost"
    if room == '--':
        room = "localhost"  # special case: docopt caught '--' as a room name

    if arguments.get('--dry-run', False):
        fabric.api.execute(task.dryrun)
    if arguments['new']:
        template_root = arguments["--template_home"] or default_obi_template_dir
        project_name = arguments['<name>']
        allowed_name_regex = "^[a-zA-Z][a-zA-Z0-9-]*$"
        if not re.match(allowed_name_regex, project_name):
            print("Name must match {0} but you entered '{1}'".format(
                allowed_name_regex, project_name))
            return 1
        template_name = arguments['<template>']
        template_path = os.path.join(template_root, template_name,
                                     template_name + ".py")
        if not os.path.exists(template_path):
            print("Could not find template {0}".format(template_name))
            print("Expected to find {0}".format(template_path))
            print("Installed templates:\n{0}".format("\n".join(
                [d for d in os.listdir(template_root)])))
            return 1
        template = imp.load_source(template_name, template_path)
        if not hasattr(template, 'obi_new'):
            print(
                "Error: template {0} does not expose a function named obi_new".
                format(template_name))
            return 1
        project_path = os.path.join(os.getcwd(), project_name)
        g_speak_home = get_g_speak_home(arguments)
        # regex to extract g-speak version number
        # if g_speak_home = "/opt/oblong/g-speak3.19"
        # then g_speak_vers = "3.19"
        g_speak_version = re.search(r'(\d+\.\d+)', g_speak_home).group()
        template.obi_new(project_path=project_path,
                         project_name=project_name,
                         g_speak_home=g_speak_home,
                         g_speak_version=g_speak_version)
        print("Project {0} created successfully!".format(arguments['<name>']))
    elif arguments['build']:
        res = fabric.api.execute(task.room_task, room, "build")
        res.update(fabric.api.execute(fabric.api.env.rsync))
        res.update(fabric.api.execute(task.build_task))
    elif arguments['go']:
        extras = arguments.get('<extras>', [])
        # Gracefully handle keyboard interrupts
        try:
            res = fabric.api.execute(task.room_task, room, "go")
            res.update(fabric.api.execute(fabric.api.env.rsync))
            res.update(fabric.api.execute(task.build_task))
            res.update(fabric.api.execute(task.stop_task))
            res.update(
                fabric.api.execute(task.launch_task, arguments['--debug'],
                                   extras))
        except KeyboardInterrupt:
            pass
    elif arguments['stop']:
        res = fabric.api.execute(task.room_task, room, "stop")
        res.update(
            fabric.api.execute(task.stop_task, arguments["--force"]
                               or arguments["-f"]))
    elif arguments['clean']:
        res = fabric.api.execute(task.room_task, room, "clean")
        res.update(fabric.api.execute(task.clean_task))
    elif arguments['rsync']:
        res = fabric.api.execute(task.room_task, room, "rsync")
        res.update(fabric.api.execute(fabric.api.env.rsync))
    elif arguments['fetch']:
        timestr = datetime.datetime.now().strftime("%Y%m%d.%H%M%S")
        fetch_dir = "fetched.{}".format(timestr)
        files = arguments.get('<file>', [])
        res = fabric.api.execute(task.room_task, room, "fetch")
        res.update(fabric.api.execute(task.stop_task))
        res.update(fabric.api.execute(task.fetch_task, fetch_dir, files))
        # Try to store git info
        try:
            git_diff = subprocess.check_output(["git", "diff", "HEAD"])
            with open(os.path.join(fetch_dir, "git.diff"),
                      "w") as git_diff_file:
                git_diff_file.write(git_diff)
        except:
            pass
        try:
            git_log = subprocess.check_output(["git", "log"])
            with open(os.path.join(fetch_dir, "git.log"), "w") as git_log_file:
                git_log_file.write(git_log)
        except:
            pass
    elif arguments['template']:
        if arguments['list']:
            template_root = arguments[
                "--template_home"] or default_obi_template_dir
            if os.path.exists(template_root):
                print("Installed templates:\n{0}".format("\n".join(
                    [d for d in os.listdir(template_root)])))
            else:
                print("No templates installed at " + template_root)
        elif arguments['install']:
            template_root = arguments[
                "--template_home"] or default_obi_template_dir
            mkdir_p(template_root)
            giturl = arguments['<giturl>']
            name = arguments['<name>'] or os.path.basename(giturl)
            if name.endswith(".git"):
                name = name[:-4]
            res = subprocess.call(["git", "clone", giturl, name],
                                  cwd=template_root)
            print("Installed template {} to {}".format(name, template_root))
            return res
        elif arguments['upgrade']:
            template_root = arguments[
                "--template_home"] or default_obi_template_dir
            if arguments["--all"]:
                retcode = 0
                for d in os.listdir(template_root):
                    dirpath = os.path.join(template_root, d)
                    if os.path.exists(dirpath):
                        print("Upgrading template at {}:".format(dirpath))
                        res = subprocess.call(["git", "pull"], cwd=dirpath)
                        if res > 0:
                            retcode = res
                return retcode

            else:
                template_name = arguments["<name>"]
                template_path = os.path.join(template_root, template_name)
                if os.path.exists(template_path):
                    res = subprocess.call(["git", "pull"], cwd=template_path)
                    print("Upgraded template at {}".format(template_path))
                    return res
                else:
                    print("No template installed with name " + template_name)
                    return 1
        elif arguments['remove']:
            template_root = arguments[
                "--template_home"] or default_obi_template_dir
            template_name = arguments["<name>"]
            template_path = os.path.join(template_root, template_name)
            if os.path.exists(template_path):
                return subprocess.call(["rm", "-rf", template_path])
            else:
                print("No template installed with name " + template_name)
                return 1
    elif arguments['room']:
        if arguments['list']:
            # converts project.yaml into Dict
            config = task.load_project_config(task.project_yaml())
            for room in sorted(config.get("rooms", {})):
                print(room)
    return 0
예제 #57
0
def pyexec(pycom, *args, pycom2=None):
    pycom2 = pycom2 or pycom
    os.execlp(pycom, pycom2, *args)
예제 #58
0
def main():
    print("number of arg : ", len(sys.argv))
    print('is : ', str(sys.argv), sys.argv[1])
    os.execlp(sys.argv[1], sys.argv[1], sys.argv[2])
    print('fin')
예제 #59
0
 def go_console(domain):
     os.execlp("virsh", "virsh", "-c", configuration.libvirt_uri, "console",
               domain.name)
예제 #60
0
def make_animation( name ):
    name_arg = 'anim/' + name + '*'
    name = name + '.gif'
    print 'Saving animation as ' + name
    execlp('convert', 'convert', '-delay', '3', name_arg, name)