示例#1
0
def tcp4_to_unix(local_port, unix_path):
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
                           socket.IPPROTO_TCP)
    server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    try:
        server.bind(('127.0.0.1', local_port))
    except socket.error as e:
        sys.stderr.write('remote cant grab port %d\n' % local_port)
        # let other end time to connect to maintain ssh up
        time.sleep(10)
        sys.exit(0)
    server.listen(32)

    while True:
        (rl, wl, el) = select.select([server], [], [server], 1)
        if server in rl:
            (client, _) = server.accept()
            if not posix.fork():
                unix = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
                try:
                    unix.connect(unix_path)
                except socket.error as e:
                    print 'Unable to grab %s: %s' % (unix_path, e)
                pipe = FdPipe(client, client, unix, unix)
                while pipe.one_loop():
                    pass
                return
            client.close()
        try:
            posix.waitpid(-1, posix.WNOHANG)
        except OSError:
            pass
示例#2
0
文件: process.py 项目: gnprice/oil
    def Start(self):
        """Start this process with fork(), haandling redirects."""
        # TODO: If OSH were a job control shell, we might need to call some of
        # these here.  They control the distribution of signals, some of which
        # originate from a terminal.  All the processes in a pipeline should be in
        # a single process group.
        #
        # - posix.setpgid()
        # - posix.setpgrp()
        # - posix.tcsetpgrp()
        #
        # NOTE: posix.setsid() isn't called by the shell; it's should be called by the
        # login program that starts the shell.
        #
        # The whole job control mechanism is complicated and hacky.

        pid = posix.fork()
        if pid < 0:
            # When does this happen?
            raise RuntimeError('Fatal error in posix.fork()')

        elif pid == 0:  # child
            for st in self.state_changes:
                st.Apply()

            self.thunk.Run()
            # Never returns

        #log('STARTED process %s, pid = %d', self, pid)

        # Invariant, after the process is started, it stores its PID.
        self.pid = pid
        return pid
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)
示例#4
0
def tcp4_to_unix(local_port, unix_path):
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
                           socket.IPPROTO_TCP)
    server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    try:
        server.bind(('127.0.0.1', local_port))
    except socket.error as e:
        sys.stderr.write('remote cant grab port %d\n' % local_port)
        # let other end time to connect to maintain ssh up
        time.sleep(10)
        sys.exit(0)
    server.listen(32)

    while True:
        (rl, wl, el) = select.select([server], [], [server], 1)
        if server in rl:
            (client, _) = server.accept()
            if not posix.fork():
                unix = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
                try:
                    unix.connect(unix_path)
                except socket.error as e:
                    print('Unable to grab %s: %s' % (unix_path, e))
                pipe = FdPipe(client, client, unix, unix)
                while pipe.one_loop():
                    pass
                return
            client.close()
        try:
            posix.waitpid(-1, posix.WNOHANG)
        except OSError:
            pass
示例#5
0
文件: intercom.py 项目: 8Banana/py1.0
def ioloop1(s, otheraddr):
    #
    # Watch out! data is in bytes, but the port counts in samples,
    # which are two bytes each (for 16-bit samples).
    # Luckily, we use mono, else it would be worse (2 samples/frame...)
    #
    SAMPSPERBUF = 500
    BYTESPERSAMP = 2  # AL.SAMPLE_16
    BUFSIZE = BYTESPERSAMP * SAMPSPERBUF
    QSIZE = 4 * SAMPSPERBUF
    #
    config = al.newconfig()
    config.setqueuesize(QSIZE)
    config.setwidth(AL.SAMPLE_16)
    config.setchannels(AL.MONO)
    #
    pid = posix.fork()
    if pid:
        # Parent -- speaker/headphones handler
        log('parent started')
        spkr = al.openport('spkr', 'w', config)
        while 1:
            data = s.recv(BUFSIZE)
            if len(data) == 0:
                # EOF packet
                log('parent got empty packet; killing child')
                posix.kill(pid, 15)
                return
            # Discard whole packet if we are too much behind
            if spkr.getfillable() > len(data) / BYTESPERSAMP:
                if len(debug) >= 2:
                    log('parent Q full; dropping packet')
                spkr.writesamps(data)
    else:
        # Child -- microphone handler
        log('child started')
        try:
            try:
                mike = al.openport('mike', 'r', config)
                # Sleep a while to let the other side get started
                time.sleep(1)
                # Drain the queue before starting to read
                data = mike.readsamps(mike.getfilled())
                # Loop, sending packets from the mike to the net
                while 1:
                    data = mike.readsamps(SAMPSPERBUF)
                    s.sendto(data, otheraddr)
            except KeyboardInterrupt:
                log('child got interrupt; exiting')
                posix._exit(0)
            except error:
                log('child got error; exiting')
                posix._exit(1)
        finally:
            log('child got unexpected error; leaving w/ traceback')
示例#6
0
def ioloop1(s, otheraddr):
	#
	# Watch out! data is in bytes, but the port counts in samples,
	# which are two bytes each (for 16-bit samples).
	# Luckily, we use mono, else it would be worse (2 samples/frame...)
	#
	SAMPSPERBUF = 500
	BYTESPERSAMP = 2 # AL.SAMPLE_16
	BUFSIZE = BYTESPERSAMP*SAMPSPERBUF
	QSIZE = 4*SAMPSPERBUF
	#
	config = al.newconfig()
	config.setqueuesize(QSIZE)
	config.setwidth(AL.SAMPLE_16)
	config.setchannels(AL.MONO)
	#
	pid = posix.fork()
	if pid:
		# Parent -- speaker/headphones handler
		log('parent started')
		spkr = al.openport('spkr', 'w', config)
		while 1:
			data = s.recv(BUFSIZE)
			if len(data) == 0:
				# EOF packet
				log('parent got empty packet; killing child')
				posix.kill(pid, 15)
				return
			# Discard whole packet if we are too much behind
			if spkr.getfillable() > len(data) / BYTESPERSAMP:
				if len(debug) >= 2:
					log('parent Q full; dropping packet')
				spkr.writesamps(data)
	else:
		# Child -- microphone handler
		log('child started')
		try:
		    try:
			    mike = al.openport('mike', 'r', config)
			    # Sleep a while to let the other side get started
			    time.sleep(1)
			    # Drain the queue before starting to read
			    data = mike.readsamps(mike.getfilled())
			    # Loop, sending packets from the mike to the net
			    while 1:
				    data = mike.readsamps(SAMPSPERBUF)
				    s.sendto(data, otheraddr)
		    except KeyboardInterrupt:
			    log('child got interrupt; exiting')
			    posix._exit(0)
		    except error:
			    log('child got error; exiting')
			    posix._exit(1)
		finally:
			log('child got unexpected error; leaving w/ traceback')
示例#7
0
 def test_exit(self):
     try:
         import posix, _rawffi
     except ImportError:
         skip("requires posix.fork() to test")
     #
     pid = posix.fork()
     if pid == 0:
         _rawffi.exit(5)   # in the child
     pid, status = posix.waitpid(pid, 0)
     assert posix.WIFEXITED(status)
     assert posix.WEXITSTATUS(status) == 5
示例#8
0
    def start(self):
        if self.__parent_pid__ == os.getpid():
            pid = posix.fork()
        else:
            pid = 0

        self.__this_pid__ = os.getpid()
        if pid:  #TODO check existence of start function
            try:
                self.__runOnStartFunc__(self.__this_pid__)
            except Exception as e:
                pp_err.pprint(e)
        return pid
示例#9
0
文件: process.py 项目: rbs-pli/oil
    def Start(self):
        """Start this process with fork(), haandling redirects."""
        # TODO: If OSH were a job control shell, we might need to call some of
        # these here.  They control the distribution of signals, some of which
        # originate from a terminal.  All the processes in a pipeline should be in
        # a single process group.
        #
        # - posix.setpgid()
        # - posix.setpgrp()
        # - posix.tcsetpgrp()
        #
        # NOTE: posix.setsid() isn't called by the shell; it's should be called by the
        # login program that starts the shell.
        #
        # The whole job control mechanism is complicated and hacky.

        pid = posix.fork()
        if pid < 0:
            # When does this happen?
            raise RuntimeError('Fatal error in posix.fork()')

        elif pid == 0:  # child
            # Respond to Ctrl-\ (core dump)
            signal.signal(signal.SIGQUIT, signal.SIG_DFL)
            # Respond to Ctrl-C
            signal.signal(signal.SIGINT, signal.SIG_DFL)

            # This doesn't make the child respond to Ctrl-Z?  Why not?  Is there
            # something at the Python level?  signalmodule.c has PyOS_AfterFork but
            # it seems OK.
            # If we add it then somehow the process stop responding to Ctrl-C too.
            #signal.signal(signal.SIGTSTP, signal.SIG_DFL)

            for st in self.state_changes:
                st.Apply()

            self.thunk.Run()
            # Never returns

        #log('STARTED process %s, pid = %d', self, pid)

        # Invariant, after the process is started, it stores its PID.
        self.pid = pid
        return pid
示例#10
0
    else:
        try:
            port = getservbyname(servicename, 'tcp')
        except error:
            sys.stderr.write(servicename + ': bad tcp service name\n')
            sys.exit(2)

    s = socket(AF_INET, SOCK_STREAM)

    try:
        s.connect((host, port))
    except error, msg:
        sys.stderr.write('connect failed: ' + ` msg ` + '\n')
        sys.exit(1)

    pid = posix.fork()

    if pid == 0:
        # child -- read stdin, write socket
        while 1:
            line = sys.stdin.readline()
            s.send(line)
    else:
        # parent -- read socket, write stdout
        iac = 0  # Interpret next char as command
        opt = ''  # Interpret next char as option
        while 1:
            data = s.recv(BUFSIZE)
            if not data:
                # EOF; kill child and exit
                sys.stderr.write('(Closed by remote host)\n')
示例#11
0
	else:
		try:
			port = getservbyname(servname, 'tcp')
		except error:
			sys.stderr.write(servname + ': bad tcp service name\n')
			sys.exit(2)
	#
	s = socket(AF_INET, SOCK_STREAM)
	#
	try:
		s.connect((host, port))
	except error, msg:
		sys.stderr.write('connect failed: ' + `msg` + '\n')
		sys.exit(1)
	#
	pid = posix.fork()
	#
	if pid == 0:
		# child -- read stdin, write socket
		while 1:
			line = sys.stdin.readline()
			s.send(line)
	else:
		# parent -- read socket, write stdout
		iac = 0		# Interpret next char as command
		opt = ''	# Interpret next char as option
		while 1:
			data = s.recv(BUFSIZE)
			if not data:
				# EOF; kill child and exit
				sys.stderr.write( '(Closed by remote host)\n')
示例#12
0
def main():
    host = sys.argv[1]
    try:
        hostaddr = gethostbyname(host)
    except error:
        sys.stderr.write(sys.argv[1] + ': bad host name\n')
        sys.exit(2)
    #
    if len(sys.argv) > 2:
        servname = sys.argv[2]
    else:
        servname = 'telnet'
    #
    if '0' <= servname[:1] <= '9':
        port = eval(servname)
    else:
        try:
            port = getservbyname(servname, 'tcp')
        except error:
            sys.stderr.write(servname + ': bad tcp service name\n')
            sys.exit(2)
    #
    s = socket(AF_INET, SOCK_STREAM)
    #
    try:
        s.connect((host, port))
    except error as msg:
        sys.stderr.write('connect failed: ' + repr(msg) + '\n')
        sys.exit(1)
    #
    pid = posix.fork()
    #
    if pid == 0:
        # child -- read stdin, write socket
        while 1:
            line = sys.stdin.readline()
            s.send(line)
    else:
        # parent -- read socket, write stdout
        iac = 0         # Interpret next char as command
        opt = ''        # Interpret next char as option
        while 1:
            data = s.recv(BUFSIZE)
            if not data:
                # EOF; kill child and exit
                sys.stderr.write( '(Closed by remote host)\n')
                posix.kill(pid, 9)
                sys.exit(1)
            cleandata = ''
            for c in data:
                if opt:
                    print(ord(c))
                    s.send(opt + c)
                    opt = ''
                elif iac:
                    iac = 0
                    if c == IAC:
                        cleandata = cleandata + c
                    elif c in (DO, DONT):
                        if c == DO: print('(DO)', end=' ')
                        else: print('(DONT)', end=' ')
                        opt = IAC + WONT
                    elif c in (WILL, WONT):
                        if c == WILL: print('(WILL)', end=' ')
                        else: print('(WONT)', end=' ')
                        opt = IAC + DONT
                    else:
                        print('(command)', ord(c))
                elif c == IAC:
                    iac = 1
                    print('(IAC)', end=' ')
                else:
                    cleandata = cleandata + c
            sys.stdout.write(cleandata)
            sys.stdout.flush()
示例#13
0
def main():
    host = sys.argv[1]
    try:
        hostaddr = gethostbyname(host)
    except error:
        sys.stderr.write(sys.argv[1] + ': bad host name\n')
        sys.exit(2)
    #
    if len(sys.argv) > 2:
        servname = sys.argv[2]
    else:
        servname = 'telnet'
    #
    if '0' <= servname[:1] <= '9':
        port = eval(servname)
    else:
        try:
            port = getservbyname(servname, 'tcp')
        except error:
            sys.stderr.write(servname + ': bad tcp service name\n')
            sys.exit(2)
    #
    s = socket(AF_INET, SOCK_STREAM)
    #
    try:
        s.connect((host, port))
    except error as msg:
        sys.stderr.write('connect failed: ' + repr(msg) + '\n')
        sys.exit(1)
    #
    pid = posix.fork()
    #
    if pid == 0:
        # child -- read stdin, write socket
        while 1:
            line = sys.stdin.readline()
            s.send(line)
    else:
        # parent -- read socket, write stdout
        iac = 0  # Interpret next char as command
        opt = ''  # Interpret next char as option
        while 1:
            data = s.recv(BUFSIZE)
            if not data:
                # EOF; kill child and exit
                sys.stderr.write('(Closed by remote host)\n')
                posix.kill(pid, 9)
                sys.exit(1)
            cleandata = ''
            for c in data:
                if opt:
                    print(ord(c))
                    s.send(opt + c)
                    opt = ''
                elif iac:
                    iac = 0
                    if c == IAC:
                        cleandata = cleandata + c
                    elif c in (DO, DONT):
                        if c == DO: print('(DO)', end=' ')
                        else: print('(DONT)', end=' ')
                        opt = IAC + WONT
                    elif c in (WILL, WONT):
                        if c == WILL: print('(WILL)', end=' ')
                        else: print('(WONT)', end=' ')
                        opt = IAC + DONT
                    else:
                        print('(command)', ord(c))
                elif c == IAC:
                    iac = 1
                    print('(IAC)', end=' ')
                else:
                    cleandata = cleandata + c
            sys.stdout.write(cleandata)
            sys.stdout.flush()
示例#14
0
# intercom -- use mike and headset to *talk* to a person on another host.
示例#15
0
#! /usr/bin/env python
# Minimal interface to the Internet telnet protocol.
#
# It refuses all telnet options and does not recognize any of the other
# telnet commands, but can still be used to connect in line-by-line mode.
# It's also useful to play with a number of other services,
# like time, finger, smtp and even ftp.
#
# Usage: telnet host [port]
#
# The port may be a service name or a decimal port number;
# it defaults to 'telnet'.

import sys, posix, time
from socket import *
BUFSIZE = 1024
# Telnet protocol characters
IAC  = chr(255)	# Interpret as command
DONT = chr(254)
DO   = chr(253)
WONT = chr(252)
WILL = chr(251)
def main():
	host = sys.argv[1]
	try:
		hostaddr = gethostbyname(host)
	except error:
		sys.stderr.write(sys.argv[1] + ': bad host name\n')
		sys.exit(2)
	#
示例#16
0
文件: __init__.py 项目: kalou/gdocker
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP)
    server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    try:
        server.bind(("127.0.0.1", local_port))
    except socket.error, e:
        sys.stderr.write("remote cant grab port %d\n" % local_port)
        # let other end time to connect to maintain ssh up
        time.sleep(10)
        sys.exit(0)
    server.listen(32)

    while True:
        (rl, wl, el) = select.select([server], [], [server], 1)
        if server in rl:
            (client, _) = server.accept()
            if not posix.fork():
                unix = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
                try:
                    unix.connect(unix_path)
                except socket.error, e:
                    print "Unable to grab %s: %s" % (unix_path, e)
                pipe = FdPipe(client, client, unix, unix)
                while pipe.one_loop():
                    pass
                return
            client.close()
        try:
            posix.waitpid(-1, posix.WNOHANG)
        except OSError:
            pass