python类AF_UNIX的实例源码

stratum_http.py 文件源码 项目:electrum-martexcoin-server 作者: martexcoin 项目源码 文件源码 阅读 36 收藏 0 点赞 0 评论 0
def __init__(self, addr, requestHandler=StratumJSONRPCRequestHandler,
                 logRequests=False, encoding=None, bind_and_activate=True,
                 address_family=socket.AF_INET):
        self.logRequests = logRequests
        StratumJSONRPCDispatcher.__init__(self, encoding)
        # TCPServer.__init__ has an extra parameter on 2.6+, so
        # check Python version and decide on how to call it
        vi = sys.version_info
        self.address_family = address_family
        if USE_UNIX_SOCKETS and address_family == socket.AF_UNIX:
            # Unix sockets can't be bound if they already exist in the
            # filesystem. The convention of e.g. X11 is to unlink
            # before binding again.
            if os.path.exists(addr):
                try:
                    os.unlink(addr)
                except OSError:
                    logging.warning("Could not unlink socket %s", addr)

        SocketServer.TCPServer.__init__(self, addr, requestHandler, bind_and_activate)

        if fcntl is not None and hasattr(fcntl, 'FD_CLOEXEC'):
            flags = fcntl.fcntl(self.fileno(), fcntl.F_GETFD)
            flags |= fcntl.FD_CLOEXEC
            fcntl.fcntl(self.fileno(), fcntl.F_SETFD, flags)
3_9a_unix_domain_socket_server.py 文件源码 项目:Python-Network-Programming-Cookbook-Second-Edition 作者: PacktPublishing 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
def run_unix_domain_socket_server():
    if os.path.exists(SERVER_PATH):
        os.remove( SERVER_PATH )

    print ("starting unix domain socket server.")
    server = socket.socket( socket.AF_UNIX, socket.SOCK_DGRAM )
    server.bind(SERVER_PATH)

    print ("Listening on path: %s" %SERVER_PATH)
    while True:
        datagram = server.recv( 1024 )
        if not datagram:
            break
        else:
            print ("-" * 20)
            print (datagram)
        if "DONE" == datagram:
            break
    print ("-" * 20)
    print ("Server is shutting down now...")
    server.close()
    os.remove(SERVER_PATH)
    print ("Server shutdown and path removed.")
server_JF.py 文件源码 项目:jf 作者: rolycg 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def query_process_communication():
    global t2
    if os.path.exists('/tmp/process_com_' + login):
        os.remove('/tmp/process_com_' + login)
    sqp = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    sqp.bind('/tmp/process_com_' + login)
    sqp.listen(1)
    while 1:
        conn_qp, _ = sqp.accept()
        while 1:
            data = conn_qp.recv(10)
            if data:
                if t2 and t2.is_alive():
                    t2.terminate()
                open_writing()
                conn_qp.close()
                break
unix_events.py 文件源码 项目:annotated-py-asyncio 作者: hhstore 项目源码 文件源码 阅读 35 收藏 0 点赞 0 评论 0
def create_unix_connection(self, protocol_factory, path, *,
                               ssl=None, sock=None,
                               server_hostname=None):
        assert server_hostname is None or isinstance(server_hostname, str)
        if ssl:
            if server_hostname is None:
                raise ValueError(
                    'you have to pass server_hostname when using ssl')
        else:
            if server_hostname is not None:
                raise ValueError('server_hostname is only meaningful with ssl')

        if path is not None:
            if sock is not None:
                raise ValueError(
                    'path and sock can not be specified at the same time')

            sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM, 0)
            try:
                sock.setblocking(False)
                yield from self.sock_connect(sock, path)
            except:
                sock.close()
                raise

        else:
            if sock is None:
                raise ValueError('no path and sock were specified')
            sock.setblocking(False)

        transport, protocol = yield from self._create_connection_transport(
            sock, protocol_factory, ssl, server_hostname)
        return transport, protocol
_pslinux.py 文件源码 项目:OSPTF 作者: xSploited 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def __init__(self):
        tcp4 = ("tcp", socket.AF_INET, socket.SOCK_STREAM)
        tcp6 = ("tcp6", socket.AF_INET6, socket.SOCK_STREAM)
        udp4 = ("udp", socket.AF_INET, socket.SOCK_DGRAM)
        udp6 = ("udp6", socket.AF_INET6, socket.SOCK_DGRAM)
        unix = ("unix", socket.AF_UNIX, None)
        self.tmap = {
            "all": (tcp4, tcp6, udp4, udp6, unix),
            "tcp": (tcp4, tcp6),
            "tcp4": (tcp4,),
            "tcp6": (tcp6,),
            "udp": (udp4, udp6),
            "udp4": (udp4,),
            "udp6": (udp6,),
            "unix": (unix,),
            "inet": (tcp4, tcp6, udp4, udp6),
            "inet4": (tcp4, udp4),
            "inet6": (tcp6, udp6),
        }
        self._procfs_path = None
handler.py 文件源码 项目:node-agent 作者: Tendrl 项目源码 文件源码 阅读 40 收藏 0 点赞 0 评论 0
def bind_unix_listener(self):
        # http://0pointer.de/blog/projects/systemd.html (search "file
        # descriptor 3")
        try:
            socket_fd = 3
            self.sock = socket.fromfd(socket_fd, socket.AF_UNIX,
                                      socket.SOCK_STREAM)
            self.sock.listen(50)
            return self.sock
        except (TypeError, BlockingIOError, socket.error, ValueError):
            pass
        try:
            self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
            if os.path.exists(MESSAGE_SOCK_PATH):
                os.remove(MESSAGE_SOCK_PATH)
            self.sock.bind(MESSAGE_SOCK_PATH)
            self.sock.listen(50)
            return self.sock
        except Exception as ex:
            exc_type, exc_value, exc_tb = sys.exc_info()
            traceback.print_exception(exc_type, exc_value, exc_tb,
                                      file=sys.stderr)
            raise ex
multiproxy.py 文件源码 项目:slidoc 作者: mitotic 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def connect_to_internal(self):
        if self.closed:
            return

        try:
            assert self.relay_address, "Relay address not defined for internal connection"
            if isinstance(self.relay_address, tuple):
                # relay_address = (host, addr)
                socket_type = socket.AF_INET
            else:
                # relay_address = unix_domain_socket_addr
                socket_type = socket.AF_UNIX
            self.internal_sock = socket.socket(socket_type, socket.SOCK_STREAM, 0)
            self.internal_stream = ChunkyIOStream(self.internal_sock, io_loop=self.proxy_server.io_loop)
            self.internal_stream.set_close_callback(self.internal_disconnected)
            self.internal_stream.connect(self.relay_address, self.internal_connected)
        except Exception, excp:
            logging.warning("multiproxy: Internal connect error: %s", excp)
            self.inbound_flow.error_response("502 Bad Gateway (internal connect error)")
test_socketserver.py 文件源码 项目:oil 作者: oilshell 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
def pickaddr(self, proto):
        if proto == socket.AF_INET:
            return (HOST, 0)
        else:
            # XXX: We need a way to tell AF_UNIX to pick its own name
            # like AF_INET provides port==0.
            dir = None
            if os.name == 'os2':
                dir = '\socket'
            fn = tempfile.mktemp(prefix='unix_socket.', dir=dir)
            if os.name == 'os2':
                # AF_UNIX socket names on OS/2 require a specific prefix
                # which can't include a drive letter and must also use
                # backslashes as directory separators
                if fn[1] == ':':
                    fn = fn[2:]
                if fn[0] in (os.sep, os.altsep):
                    fn = fn[1:]
                if os.sep == '/':
                    fn = fn.replace(os.sep, os.altsep)
                else:
                    fn = fn.replace(os.altsep, os.sep)
            self.test_files.append(fn)
            return fn
sockets.py 文件源码 项目:logging2 作者: vforgione 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def _create_name(self) -> str:
        """Creates the name for the handler - called from ``__init__`` if a name is not given.

        :returns: a template of `({protocol} )?{host}(:{port})?`
        """
        if self.port:
            port = ':{}'.format(self.port)
        else:
            port = ''

        if self.family == socket.AF_UNIX:
            stype = 'UNIX'
        elif self.type == socket.SOCK_STREAM:
            stype = 'TCP'
        elif self.type == socket.SOCK_DGRAM:
            stype = 'UDP'
        else:
            stype = None  # pragma: no cover

        if stype:
            host = ' {}'.format(self.host)
        else:
            host = self.host  # pragma: no cover

        return '{}{}{}'.format(stype, host, port)
sockets.py 文件源码 项目:logging2 作者: vforgione 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def __init__(
            self,
            node: str,
            encoding: Optional[str]='utf8',
            name: Optional[str]=None,
            level: Optional[LogLevel]=None
    ):
        """Instantiates a new ``UnixHandler``

        :param node: the path to the socket node on the system
        :param encoding: the message encoding
        :param name: the name of the handler
        :param level: the minimum verbosity level to write log entries
        """
        super().__init__(
            name=name, level=level, host=node, family=socket.AF_UNIX,
            type=socket.SOCK_DGRAM, encoding=encoding)
blueserver.py 文件源码 项目:bluetool 作者: emlid 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def NewConnection(self, path, fd, properties):
        address = str(path)
        address = address[len(address) - 17:len(address)]
        address = address.replace("_", ":")
        print_info("Connected: {}\n".format(address))

        blue_socket = socket.fromfd(
            fd.take(), socket.AF_UNIX, socket.SOCK_STREAM)

        socket_sink = SocketSink(sock=blue_socket)
        self.bridge = TCPBridge(
            sink=socket_sink,
            port_in=self.tcp_port_in,
            port_out=self.tcp_port_out)

        try:
            self.bridge.start(in_background=False)
        except TCPBridgeError as error:
            print_error(str(error) + "\n")

        self.bridge.stop()
        blue_socket.close()

        print_info("Disconnected: {}\n".format(address))
        Bluetooth().disconnect(address)
test_asyncore.py 文件源码 项目:web_ctp 作者: molebot 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def test_handle_expt(self):
        # Make sure handle_expt is called on OOB data received.
        # Note: this might fail on some platforms as OOB data is
        # tenuously supported and rarely used.
        if HAS_UNIX_SOCKETS and self.family == socket.AF_UNIX:
            self.skipTest("Not applicable to AF_UNIX sockets.")

        class TestClient(BaseClient):
            def handle_expt(self):
                self.socket.recv(1024, socket.MSG_OOB)
                self.flag = True

        class TestHandler(BaseTestHandler):
            def __init__(self, conn):
                BaseTestHandler.__init__(self, conn)
                self.socket.send(bytes(chr(244), 'latin-1'), socket.MSG_OOB)

        server = BaseServer(self.family, self.addr, TestHandler)
        client = TestClient(self.family, server.address)
        self.loop_waiting_for_flag(client)
basehandler.py 文件源码 项目:dcos 作者: dcos 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def log_message(self, log_format, *args):
        """Just a patch to make Mockers Requests Handlers compatible with
           Unix Sockets.

        Method logs the request without source IP address/with hard-coded value
        of `unix-socket-connection` if the socket is a Unix Socket.

        Please check the http.server.BaseHTTPRequestHandler documentation
        for the meaning of the function arguments.
        """
        endpoint_id = self.server.context.data['endpoint_id']
        if self.server.address_family == socket.AF_UNIX:
            log.debug("[Endpoint: %s] %s - - [%s] %s\n",
                      endpoint_id,
                      "unix-socket-connection",
                      self.log_date_time_string(),
                      log_format % args)
        else:
            log.debug("[Endpoint: %s] %s - - [%s] %s\n",
                      endpoint_id,
                      self.address_string(),
                      self.log_date_time_string(),
                      log_format % args)
selector_events.py 文件源码 项目:golightan 作者: shirou 项目源码 文件源码 阅读 36 收藏 0 点赞 0 评论 0
def sock_connect(self, sock, address):
        """Connect to a remote socket at address.

        This method is a coroutine.
        """
        if self._debug and sock.gettimeout() != 0:
            raise ValueError("the socket must be non-blocking")

        if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX:
            resolved = base_events._ensure_resolved(
                address, family=sock.family, proto=sock.proto, loop=self)
            if not resolved.done():
                yield from resolved
            _, _, _, _, address = resolved.result()[0]

        fut = self.create_future()
        self._sock_connect(fut, sock, address)
        return (yield from fut)
bluetoothspp.py 文件源码 项目:CodeLabs 作者: TheIoTLearningInitiative 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def NewConnection(self, path, fd, properties):
        self.fd = fd.take()
        print("NewConnection(%s, %d)" % (path, self.fd))


        server_sock = socket.fromfd(self.fd, socket.AF_UNIX, socket.SOCK_STREAM)
        server_sock.setblocking(1)
        server_sock.send("This is Edison SPP loopback test\nAll data will be loopback\nPlease start:\n")

        myfifo.openFifo()

        print('enter recv loop\n')
        try:
            while True:
                data = server_sock.recv(1024)
                print("received: %s" % data)
                myfifo.writeFifo(data)
                #server_sock.send("looping back: %s\n" % data)
        except IOError as err:
            print (err)
            pass

        server_sock.close()
        print("all done")
SPP-loopback.py 文件源码 项目:CodeLabs 作者: TheIoTLearningInitiative 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def NewConnection(self, path, fd, properties):
        self.fd = fd.take()
        print("NewConnection(%s, %d)" % (path, self.fd))


        server_sock = socket.fromfd(self.fd, socket.AF_UNIX, socket.SOCK_STREAM)
        server_sock.setblocking(1)
        server_sock.send("This is Edison SPP loopback test\nAll data will be loopback\nPlease start:\n")

        try:
            while True:
                data = server_sock.recv(1024)
                print("received: %s" % data)
            server_sock.send("looping back: %s\n" % data)
        except IOError:
            pass

        server_sock.close()
        print("all done")
spp.py 文件源码 项目:CodeLabs 作者: TheIoTLearningInitiative 项目源码 文件源码 阅读 39 收藏 0 点赞 0 评论 0
def NewConnection(self, path, fd, properties):
        self.fd = fd.take()
                device_path = os.path.basename(path)
        print("\nConnected to %s\nPress [ENTER] to continue" % device_path)

        server_sock = socket.fromfd(self.fd, socket.AF_UNIX, socket.SOCK_STREAM)
        server_sock.settimeout(1)
        server_sock.send("Hello, this is Edison!")
        try:
            while True:
                        try:
                            data = server_sock.recv(1024)
                            gardening_system.function(data)
                            if data == 'b':
                                server_sock.send(gardening_system.requestData())
                        except socket.timeout:
                            pass
                        gardening_system.myProgram()
        except IOError:
            pass
        server_sock.close()
                print("\nYour device is now disconnected\nPress [ENTER] to continue")
spp.py 文件源码 项目:CodeLabs 作者: TheIoTLearningInitiative 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def processSockets(fd):
    data = ""
    server_sock = socket.fromfd(fd,
                                socket.AF_UNIX,
                                socket.SOCK_STREAM)
    server_sock.settimeout(1)
    server_sock.send("Hello, this is Edison!")
    try:
        while not closing:
            try:
                data = server_sock.recv(1024)
                print ("Here's data %s" % data)
                result = ha.callFunction(data)
                if result:
                    server_sock.send(result)
            except socket.timeout:
                pass
    except IOError:
        pass
    server_sock.close()


# Agent class
spp.py 文件源码 项目:CodeLabs 作者: TheIoTLearningInitiative 项目源码 文件源码 阅读 36 收藏 0 点赞 0 评论 0
def NewConnection(self, path, fd, properties):
        self.fd = fd.take()
                device_path = os.path.basename(path)
        print("\nConnected to %s\nPress [ENTER] to continue" % device_path)

        server_sock = socket.fromfd(self.fd, socket.AF_UNIX, socket.SOCK_STREAM)
        server_sock.settimeout(1)
        server_sock.send("Hello, this is Edison!")
        try:
            while True:
                        try:
                            data = server_sock.recv(1024)
                            temperature_monitor.function(data)
                            if data == 'get':
                                server_sock.send(temperature_monitor.requestData())
                        except socket.timeout:
                            pass
                        temperature_monitor.myProgram()
        except IOError:
            pass
        server_sock.close()
                print("\nYour device is now disconnected\nPress [ENTER] to continue")
reduction.py 文件源码 项目:ouroboros 作者: pybee 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def recvfds(sock, size):
        '''Receive an array of fds over an AF_UNIX socket.'''
        a = array.array('i')
        bytes_size = a.itemsize * size
        msg, ancdata, flags, addr = sock.recvmsg(1, socket.CMSG_LEN(bytes_size))
        if not msg and not ancdata:
            raise EOFError
        try:
            if ACKNOWLEDGE:
                sock.send(b'A')
            if len(ancdata) != 1:
                raise RuntimeError('received %d items of ancdata' %
                                   len(ancdata))
            cmsg_level, cmsg_type, cmsg_data = ancdata[0]
            if (cmsg_level == socket.SOL_SOCKET and
                cmsg_type == socket.SCM_RIGHTS):
                if len(cmsg_data) % a.itemsize != 0:
                    raise ValueError
                a.frombytes(cmsg_data)
                assert len(a) % 256 == msg[0]
                return list(a)
        except (ValueError, IndexError):
            pass
        raise RuntimeError('Invalid data received')
test_asyncore.py 文件源码 项目:ouroboros 作者: pybee 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def test_handle_expt(self):
        # Make sure handle_expt is called on OOB data received.
        # Note: this might fail on some platforms as OOB data is
        # tenuously supported and rarely used.
        if HAS_UNIX_SOCKETS and self.family == socket.AF_UNIX:
            self.skipTest("Not applicable to AF_UNIX sockets.")

        class TestClient(BaseClient):
            def handle_expt(self):
                self.socket.recv(1024, socket.MSG_OOB)
                self.flag = True

        class TestHandler(BaseTestHandler):
            def __init__(self, conn):
                BaseTestHandler.__init__(self, conn)
                self.socket.send(bytes(chr(244), 'latin-1'), socket.MSG_OOB)

        server = BaseServer(self.family, self.addr, TestHandler)
        client = TestClient(self.family, server.address)
        self.loop_waiting_for_flag(client)
test_asyncore.py 文件源码 项目:ouroboros 作者: pybee 项目源码 文件源码 阅读 36 收藏 0 点赞 0 评论 0
def test_set_reuse_addr(self):
        if HAS_UNIX_SOCKETS and self.family == socket.AF_UNIX:
            self.skipTest("Not applicable to AF_UNIX sockets.")
        sock = socket.socket(self.family)
        try:
            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        except OSError:
            unittest.skip("SO_REUSEADDR not supported on this platform")
        else:
            # if SO_REUSEADDR succeeded for sock we expect asyncore
            # to do the same
            s = asyncore.dispatcher(socket.socket(self.family))
            self.assertFalse(s.socket.getsockopt(socket.SOL_SOCKET,
                                                 socket.SO_REUSEADDR))
            s.socket.close()
            s.create_socket(self.family)
            s.set_reuse_addr()
            self.assertTrue(s.socket.getsockopt(socket.SOL_SOCKET,
                                                 socket.SO_REUSEADDR))
        finally:
            sock.close()
handlers.py 文件源码 项目:ouroboros 作者: pybee 项目源码 文件源码 阅读 35 收藏 0 点赞 0 评论 0
def makeSocket(self, timeout=1):
        """
        A factory method which allows subclasses to define the precise
        type of socket they want.
        """
        if self.port is not None:
            result = socket.create_connection(self.address, timeout=timeout)
        else:
            result = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
            result.settimeout(timeout)
            try:
                result.connect(self.address)
            except OSError:
                result.close()  # Issue 19182
                raise
        return result
handlers.py 文件源码 项目:ouroboros 作者: pybee 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def _connect_unixsocket(self, address):
        use_socktype = self.socktype
        if use_socktype is None:
            use_socktype = socket.SOCK_DGRAM
        self.socket = socket.socket(socket.AF_UNIX, use_socktype)
        try:
            self.socket.connect(address)
            # it worked, so set self.socktype to the used type
            self.socktype = use_socktype
        except OSError:
            self.socket.close()
            if self.socktype is not None:
                # user didn't specify falling back, so fail
                raise
            use_socktype = socket.SOCK_STREAM
            self.socket = socket.socket(socket.AF_UNIX, use_socktype)
            try:
                self.socket.connect(address)
                # it worked, so set self.socktype to the used type
                self.socktype = use_socktype
            except OSError:
                self.socket.close()
                raise
easy_application.py 文件源码 项目:ops_agent 作者: sjqzhang 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
def bind_unix_listener(self, path, backlog=50, user=None):
        try:
            sock = gevent.socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
            sock.setblocking(0)
            self.unlink(path)
            sock.bind(path)
            if user is not None:
                import pwd
                user = pwd.getpwnam(user)
                os.chown(path, user.pw_uid, user.pw_gid)
            os.chmod(path, 0777)
            sock.listen(backlog)
        except Exception, e:
            self.logger.error("Create unix socket failed: %s", e.__str__())
            return None
        return sock
pullpipe.py 文件源码 项目:zenchmarks 作者: squeaky-pl 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def recvfd(socketfd):
    """
    Receive a file descriptor from a L{sendmsg} message on the given C{AF_UNIX}
    socket.

    @param socketfd: An C{AF_UNIX} socket, attached to another process waiting
        to send sockets via the ancillary data mechanism in L{send1msg}.

    @param fd: C{int}

    @return: a 2-tuple of (new file descriptor, description).
    @rtype: 2-tuple of (C{int}, C{bytes})
    """
    ourSocket = socket.fromfd(socketfd, socket.AF_UNIX, socket.SOCK_STREAM)
    data, ancillary, flags = recvmsg(ourSocket)
    [(cmsgLevel, cmsgType, packedFD)] = ancillary
    # cmsgLevel and cmsgType really need to be SOL_SOCKET / SCM_RIGHTS, but
    # since those are the *only* standard values, there's not much point in
    # checking.
    [unpackedFD] = unpack("i", packedFD)
    return (unpackedFD, data)
netstat.py 文件源码 项目:membrane 作者: CrySyS 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def render_text(self, outfd, data):
        linux_common.set_plugin_members(self)

        if not self.addr_space.profile.has_type("inet_sock"):
            # ancient (2.6.9) centos kernels do not have inet_sock in debug info
            raise AttributeError, "Given profile does not have inet_sock, please file a bug if the kernel version is > 2.6.11"

        for task in data:
            for ents in task.netstat():
                if ents[0] == socket.AF_INET:
                    (proto, saddr, sport, daddr, dport, state) = ents[1]
                    outfd.write("{0:8s} {1:<16}:{2:>5} {3:<16}:{4:>5} {5:<15s} {6:>17s}/{7:<5d}\n".format(proto, saddr, sport, daddr, dport, state, task.comm, task.pid))

                elif ents[0] == socket.AF_UNIX and not self._config.IGNORE_UNIX:
                    (name, inum) = ents[1]
                    outfd.write("UNIX {0:<8d} {1:>17s}/{2:<5d} {3:s}\n".format(inum, task.comm, task.pid, name))
test_datastore.py 文件源码 项目:felix 作者: axbaretto 项目源码 文件源码 阅读 36 收藏 0 点赞 0 评论 0
def test_start_driver(self, m_unlink, m_socket, m_timeout, m_popen,
                          m_exists):
        m_exists.return_value = True
        m_sck = Mock()
        m_socket.return_value = m_sck
        m_conn = Mock()
        m_sck.accept.return_value = m_conn, None
        reader, writer = self.watcher._start_driver()
        self.assertEqual(m_socket.mock_calls[0], call(socket.AF_UNIX,
                                                      socket.SOCK_STREAM))
        self.assertEqual(m_sck.bind.mock_calls,
                         [call("/run/felix-driver.sck")])
        self.assertEqual(m_sck.listen.mock_calls, [call(1)])
        self.assertEqual(m_popen.mock_calls[0],
                         call([ANY, "-m", "calico.etcddriver",
                               "/run/felix-driver.sck"]))
        self.assertEqual(m_unlink.mock_calls,
                         [call("/run/felix-driver.sck")] * 2)
        self.assertTrue(isinstance(reader, MessageReader))
        self.assertTrue(isinstance(writer, MessageWriter))
        m_exists.assert_called_once_with("/run")
        m_timeout.assert_called_once_with(10)
server_JF.py 文件源码 项目:jf 作者: rolycg 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def finish_query(devices, data_layer, son):
    res = {}
    for x in devices.keys():
        for item in devices[x]:
            try:
                res[repr((x[0], x[1], x[2], x[3]))].append(repr(data_layer.get_address(item[1], item[7])))
            except KeyError:
                res[repr((x[0], x[1], x[2], x[3]))] = [repr(data_layer.get_address(item[1], item[7]))]
    s_qp = socket.socket(family=socket.AF_UNIX, type=socket.SOCK_STREAM)
    son.send(json.dumps(res))
    for x in devices.keys():
        devices[x].close()
    data_layer.close()
    try:
        s_qp.connect('/tmp/process_com_' + login)
    except FileNotFoundError:
        print('FileNotFoundError')
    except ConnectionRefusedError:
        print('ConnectionRefusedError')
    s_qp.send(b'True')
    s_qp.close()
client_JF.py 文件源码 项目:jf 作者: rolycg 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def sign_in(s):
    logged = s.recv(100)
    logged = logged.decode()
    logged = json.loads(logged)
    if logged['logged']:
        return s
    password = getpass.getpass()
    sha = hashlib.md5(password.encode()).hexdigest()
    j = json.dumps({'action': 'login', 'password': sha})
    s.send(j.encode())
    d = s.recv(2048)
    d = json.loads(d.decode())
    try:
        message = d['login']
        if not message:
            print('Wrong password.')
            s.close()
            return None
        else:
            s = socket.socket(family=socket.AF_UNIX, type=socket.SOCK_STREAM)
            s.connect('/tmp/JF_' + login)
            return s
    except KeyError:
        print(error)


问题


面经


文章

微信
公众号

扫码关注公众号