def execute_command():
    pipe_fd = posix.pipe()
    pid = posix.fork()
    if pid == 0:
        cmdline = ["lsblk"]
        if check_fs_val.get() or check_UUID_val.get():
            cmdline.append("-o")
            col = "+"
            if check_fs_val.get():
                col += "fstype"
            if check_fs_val.get() and check_UUID_val.get():
                col += ","
            if check_UUID_val.get():
                col += "UUID"
            cmdline.append(col)
        posix.dup2(pipe_fd[1], 1)
        posix.close(pipe_fd[0])
        posix.close(pipe_fd[1])
        posix.execv("/bin/lsblk", cmdline)
        quit()
    else:
        posix.close(pipe_fd[1])
        ret = bytearray()
        readbytes = posix.read(pipe_fd[0], 1000)
        while readbytes != b"":
            ret += readbytes
            readbytes = posix.read(pipe_fd[0], 1000)
        posix.close(pipe_fd[0])
        posix.wait()
        return str(ret, sys.stdout.encoding)
Example #2
0
    def Pop(self):
        frame = self.stack.pop()
        #log('< Pop %s', frame)
        for saved, orig in reversed(frame.saved):
            try:
                posix.dup2(saved, orig)
            except OSError as e:
                log('dup2(%d, %d) error: %s', saved, orig, e)
                #log('fd state:')
                #posix.system('ls -l /proc/%s/fd' % posix.getpid())
                raise
            posix.close(saved)
            #log('dup2 %s %s', saved, orig)

            # NOTE: This balances the increments from _PushDup().  But it doesn't
            # balance the ones from Open().
            self.next_fd -= 1  # Count down
            assert self.next_fd >= 10, self.next_fd

        for fd in frame.need_close:
            #log('Close %d', fd)
            try:
                posix.close(fd)
            except OSError as e:
                log('Error closing descriptor %d: %s', fd, e)
                raise

        # Wait for here doc processes to finish.
        for proc, waiter in frame.need_wait:
            unused_status = proc.WaitUntilDone(waiter)
Example #3
0
    def Pop(self):
        frame = self.stack.pop()
        #log('< Pop %s', frame)
        for saved, orig in reversed(frame.saved):
            try:
                posix.dup2(saved, orig)
            except OSError as e:
                log('dup2(%d, %d) error: %s', saved, orig, e)
                #log('fd state:')
                #posix.system('ls -l /proc/%s/fd' % posix.getpid())
                raise
            posix.close(saved)
            #log('dup2 %s %s', saved, orig)

        for fd in frame.need_close:
            #log('Close %d', fd)
            try:
                posix.close(fd)
            except OSError as e:
                log('Error closing descriptor %d: %s', fd, e)
                raise

        # Wait for here doc processes to finish.
        for proc, waiter in frame.need_wait:
            unused_status = proc.WaitUntilDone(waiter)
Example #4
0
    def Open(self, path, mode='r'):
        """Opens a path for read, but moves it out of the reserved 3-9 fd range.

    Returns:
      A Python file object.  The caller is responsible for Close().

    Raises:
      OSError if the path can't be found.
    """
        if mode == 'r':
            fd_mode = posix.O_RDONLY
        elif mode == 'w':
            fd_mode = posix.O_CREAT | posix.O_RDWR
        else:
            raise AssertionError(mode)

        fd = posix.open(path, fd_mode, 0666)  # may raise OSError
        new_fd = self._GetFreeDescriptor()
        posix.dup2(fd, new_fd)
        posix.close(fd)
        try:
            f = posix.fdopen(new_fd, mode)  # Might raise IOError
        except IOError as e:
            raise OSError(*e.args)  # Consistently raise OSError
        return f
Example #5
0
def main():
	if len(sys.argv) < 2:
		print "Argument missing, usage:\n"
		print "\t$ python %s process_name\n" %(sys.argv[0])
		sys.exit(0)

	readfd, writefd = posix.pipe()
	pid = os.fork()

	if pid:
    		os.close(writefd) # use os.close() to close a file descriptor

    		readfd = os.fdopen(readfd)
    		output = readfd.read()
		output = output.replace("\n", " ")		
    		
		os.waitpid(pid, 0) # make sure the child process gets cleaned up

		print "Killing " + output
		os.system("/bin/kill -9 " + output)
	else:
    		os.close(readfd)
		posix.dup2(writefd, 1)

		os.system("/usr/bin/pgrep " + sys.argv[1])
Example #6
0
    def dup2(self, fd):
        import posix

        if not hasattr(posix, "fdopen"):
            raise AttributeError, "dup() method unavailable"
        posix.dup2(self._file_.fileno(), fd)
        return posix.fdopen(fd, self._file_.mode)
Example #7
0
    def dup2(self, fd):
	import posix

	try: ignore = posix.fdopen
	except: raise AttributeError, 'dup() method unavailable'

	posix.dup2(self._file_.fileno(), fd)
	return posix.fdopen(fd, self._file_.mode)
Example #8
0
    def dup2(self, fd):
        import posix

        if not hasattr(posix, 'fdopen'):
            raise AttributeError, 'dup() method unavailable'

        posix.dup2(self._file_.fileno(), fd)
        return posix.fdopen(fd, self._file_.mode)
 def test_dup2(self):
     if hasattr(posix, 'dup2'):
         fp1 = open(test_support.TESTFN)
         fp2 = open(test_support.TESTFN)
         try:
             posix.dup2(fp1.fileno(), fp2.fileno())
         finally:
             fp1.close()
             fp2.close()
Example #10
0
    def dup2(self, fd):
        import posix

        try:
            ignore = posix.fdopen
        except:
            raise AttributeError, 'dup() method unavailable'

        posix.dup2(self._file_.fileno(), fd)
        return posix.fdopen(fd, self._file_.mode)
Example #11
0
    def _PushDup(self, fd1, fd2):
        """Save fd2, and dup fd1 onto fd2.

    Mutates self.cur_frame.saved.

    Returns:
      success Bool
    """
        new_fd = self._NextFreeFileDescriptor()
        #log('---- _PushDup %s %s', fd1, fd2)
        need_restore = True
        try:
            #log('DUPFD %s %s', fd2, self.next_fd)
            fcntl.fcntl(fd2, fcntl.F_DUPFD, new_fd)
        except IOError as e:
            # Example program that causes this error: exec 4>&1.  Descriptor 4 isn't
            # open.
            # This seems to be ignored in dash too in savefd()?
            if e.errno == errno.EBADF:
                #log('ERROR %s', e)
                need_restore = False
            else:
                raise
        else:
            posix.close(fd2)
            fcntl.fcntl(new_fd, fcntl.F_SETFD, fcntl.FD_CLOEXEC)

        #log('==== dup %s %s\n' % (fd1, fd2))
        try:
            posix.dup2(fd1, fd2)
        except OSError as e:
            # bash/dash give this error too, e.g. for 'echo hi 1>&3'
            util.error('%d: %s', fd1, posix.strerror(e.errno))
            # Restore and return error
            posix.dup2(new_fd, fd2)
            posix.close(new_fd)
            # Undo it
            return False

        if need_restore:
            self.cur_frame.saved.append((new_fd, fd2))
        return True
Example #12
0
    def Open(self, path, mode='r'):
        """Opens a path for read, but moves it out of the reserved 3-9 fd range.

    Returns:
      A Python file object.  The caller is responsible for Close().

    Raises:
      OSError if the path can't be found.
    """
        if mode == 'r':
            fd_mode = posix.O_RDONLY
        elif mode == 'w':
            fd_mode = posix.O_CREAT | posix.O_RDWR
        else:
            raise AssertionError(mode)

        fd = posix.open(path, fd_mode, 0666)
        new_fd = self._NextFreeFileDescriptor()
        posix.dup2(fd, new_fd)
        posix.close(fd)
        return posix.fdopen(new_fd, mode)
Example #13
0
    def Apply(self):
        posix.dup2(self.w, 1)
        posix.close(self.w)  # close after dup

        posix.close(self.r)  # we're writing to the pipe, not reading
Example #14
0
    def Apply(self):
        posix.dup2(self.r, 0)
        posix.close(self.r)  # close after dup

        posix.close(self.w)  # we're reading from the pipe, not writing
def main():
    # stdin is dup'ed to make sure nothing unexpected is written or read from the
    # stream. CellAppMgr is informed of the appropriate file descriptor via its
    # command line arguments.
    fd = posix.dup(0)

    nullFD = posix.open("/dev/null", posix.O_RDWR)
    posix.dup2(nullFD, 0)
    posix.dup2(nullFD, 1)
    posix.dup2(nullFD, 2)

    connection = Connection(fd)

    peerString = connection.socket.getpeername()[0]

    syslog.syslog("Got connection from " + peerString)

    versionNumber, = connection.getStruct("=i")

    if versionNumber not in VERSION_NUMBERS:
        connection.sendMsg(
          "ERROR: Invalid local CellAppMgr version. " \
          "Expected versions %s. Got %d\n" % \
          (str( VERSION_NUMBERS ), versionNumber) )
        sys.exit(0)

    accountNameLen, = connection.getStruct("=i")
    accountName = connection.receive(accountNameLen)

    # Make a unique token that will be sent to the front-end, signed and then
    # returned.
    sentToken = str(time.time()) + str(random.random()) + peerString

    connection.socket.send(
        struct.pack("=Hi", MSG_INIT, len(sentToken)) + sentToken)

    signedTokenLen, = connection.getStruct("=i")
    signedToken = connection.receive(signedTokenLen)

    isVerified, receivedToken, decryptData = verifyToken(signedToken)

    if receivedToken != sentToken:
        syslog.syslog("Authentication failed '%s' at '%s')" %
                      (accountName, peerString))

    if not isVerified:
        connection.sendMsg("ERROR: Authentication failed for GPG key '%s'.\n" %
                           accountName)
        connection.sendMsg(
            "ERROR: Make sure the public GPG key is registered with BigWorld.\n"
        )
        connection.sendMsg(
            "ERROR: To register a key, please contact [email protected]\n"
        )
        syslog.syslog("Authentication failed for '%s' at '%s')" %
                      (accountName, peerString))
        sys.exit(0)

    remoteUID, remotePID, remoteViewerPort = \
     connection.getStruct( "=iiH" )

    syslogPrefix = "CellAppMgr:%s:%s:%d:%d" % \
      (accountName, connection.socket.getpeername()[0],
       remoteUID, remotePID )
    syslog.openlog(syslogPrefix)
    syslog.syslog("Started")
    for line in decryptData.split("\n"):
        syslog.syslog(line)

    # Read the command line arguments
    args = []
    argLen = 1
    while argLen:
        argLen, = connection.getStruct("=i")
        if argLen:
            arg = connection.receive(argLen)
            args.append(arg)

    try:
        # This affects where core files are created.
        os.chdir(os.path.dirname(EXE_PATH))
    except Exception, e:
        pass
Example #16
0
def redirect_stdout(file_name):
    file = open(file_name, "w")
    posix.dup2(file.fileno(), 1)
Example #17
0
def redirect_stdout(file_name):
    file = open(file_name, "w")
    posix.dup2(file.fileno(), 1)
Example #18
0
"""Extended file operations available in POSIX.