我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用socket.AF_UNIX。
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)
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.")
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
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
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
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
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)")
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
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)
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)
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)
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)
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)
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)
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")
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")
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")
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
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")
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')
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()
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
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
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
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)
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))
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)
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()
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)
def socketpair(): s1, s2 = eunuchs.socketpair.socketpair() p, c = (socket.fromfd(s1, socket.AF_UNIX, socket.SOCK_STREAM), socket.fromfd(s2, socket.AF_UNIX, socket.SOCK_STREAM)) os.close(s1) os.close(s2) return p, c
def __init__(self, addr, certfile, keyfile, requestHandler=SSLRequestHandler, 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) SSLTCPServer.__init__(self, addr, certfile, keyfile, 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)
def _start_worker(self): env = dict(os.environ) env["ABUSEHELPER_SUBPROCESS"] = "" # Find out the full package & module name. Don't refer to the # variable __loader__ directly to keep flake8 (version 2.5.0) # linter happy. fullname = globals()["__loader__"].fullname own_conn, other_conn = native_socket.socketpair(socket.AF_UNIX, socket.SOCK_STREAM) try: process = subprocess.Popen( [sys.executable, "-m", fullname], preexec_fn=os.setpgrp, stdin=other_conn.fileno(), close_fds=True, env=env ) try: conn = socket.fromfd(own_conn.fileno(), socket.AF_UNIX, socket.SOCK_STREAM) except: process.terminate() process.wait() raise finally: own_conn.close() other_conn.close() return process, conn
def __init__(self): self.handle = nfq.nfq_open() self.fileno = nfq.nfq_fd(self.handle) self.socket = socket.fromfd(self.fileno, socket.AF_UNIX, socket.SOCK_RAW) if nfq.nfq_unbind_pf(self.handle, socket.AF_INET) < 0: raise OSError('nfq_unbind_pf() failed. Are you root?') if nfq.nfq_bind_pf(self.handle, socket.AF_INET) < 0: raise OSError('nfq_bind_pf() failed. Are you root?')
def _compiler_build(compiler, code, time_limit_ns, memory_limit_bytes, process_limit): loop = get_event_loop() sandbox = await _sandbox_pool.get() try: await compiler.prepare(sandbox, code.encode()) output_file = path.join(sandbox.in_dir, 'output') mkfifo(output_file) with socket(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK) as cgroup_sock: cgroup_sock.bind(path.join(sandbox.in_dir, 'cgroup')) cgroup_sock.listen() build_task = loop.create_task(compiler.build( sandbox, output_file='/in/output', cgroup_file='/in/cgroup')) others_task = gather(read_pipe(output_file, _MAX_OUTPUT), wait_cgroup(cgroup_sock, build_task, time_limit_ns, memory_limit_bytes, process_limit)) package, status = await build_task output, (time_usage_ns, memory_usage_bytes) = await others_task return package, output.decode(encoding='utf-8', errors='replace'), \ time_usage_ns, memory_usage_bytes finally: _sandbox_pool.put_nowait(sandbox)
def enter_cgroup(socket_path): with socket(AF_UNIX, SOCK_STREAM) as sock: sock.connect(socket_path) sock.recv(1)
def __init__(self, interfaces: Iterable[VPPInterface], listen_socket: socket.socket, marks: Iterable[str] = None): """ Initialise VPP listener. :param interfaces: The interfaces we listen to and their information :param listen_socket: The socket we are listening on, may be a unicast or multicast socket :param marks: Marks attached to this listener """ self.interfaces = interfaces self.listen_socket = listen_socket self.marks = list(marks or []) # Check that we have Unix Domain sockets if self.listen_socket.family != socket.AF_UNIX or self.listen_socket.type != socket.SOCK_DGRAM: raise ListeningSocketError("Listen socket has to be Unix domain datagram socket")
def process_inet(self, file, family, type_, inodes, filter_pid=None): """Parse /proc/net/tcp* and /proc/net/udp* files.""" if file.endswith('6') and not os.path.exists(file): # IPv6 not supported return with open_text(file, buffering=BIGGER_FILE_BUFFERING) as f: f.readline() # skip the first line for lineno, line in enumerate(f, 1): try: _, laddr, raddr, status, _, _, _, _, _, inode = \ line.split()[:10] except ValueError: raise RuntimeError( "error while parsing %s; malformed line %s %r" % ( file, lineno, line)) if inode in inodes: # # We assume inet sockets are unique, so we error # # out if there are multiple references to the # # same inode. We won't do this for UNIX sockets. # if len(inodes[inode]) > 1 and family != socket.AF_UNIX: # raise ValueError("ambiguos inode with multiple " # "PIDs references") pid, fd = inodes[inode][0] else: pid, fd = None, -1 if filter_pid is not None and filter_pid != pid: continue else: if type_ == socket.SOCK_STREAM: status = TCP_STATUSES[status] else: status = _common.CONN_NONE try: laddr = self.decode_address(laddr, family) raddr = self.decode_address(raddr, family) except _Ipv6UnsupportedError: continue yield (fd, family, type_, laddr, raddr, status, pid)
def _get_unix_sockets(self, pid): """Get UNIX sockets used by process by parsing 'pfiles' output.""" # TODO: rewrite this in C (...but the damn netstat source code # does not include this part! Argh!!) cmd = "pfiles %s" % pid p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = p.communicate() if PY3: stdout, stderr = [x.decode(sys.stdout.encoding) for x in (stdout, stderr)] if p.returncode != 0: if 'permission denied' in stderr.lower(): raise AccessDenied(self.pid, self._name) if 'no such process' in stderr.lower(): raise NoSuchProcess(self.pid, self._name) raise RuntimeError("%r command error\n%s" % (cmd, stderr)) lines = stdout.split('\n')[2:] for i, line in enumerate(lines): line = line.lstrip() if line.startswith('sockname: AF_UNIX'): path = line.split(' ', 2)[2] type = lines[i - 2].strip() if type == 'SOCK_STREAM': type = socket.SOCK_STREAM elif type == 'SOCK_DGRAM': type = socket.SOCK_DGRAM else: type = -1 yield (-1, socket.AF_UNIX, type, path, "", _common.CONN_NONE)
def cmd(id, args, socket_path, per_cmd_connection): from socket import socket, AF_UNIX, SOCK_STREAM sock = socket(AF_UNIX, SOCK_STREAM) sock.connect(socket) try: msg = '%s %s' % (id, args) sock.send(msg.encode()) resp = sock.recv(4096) print(resp) finally: sock.close()
def read_ha_proxy_stats(haproxy_stats_socket): conn = socket(AF_UNIX, SOCK_STREAM) try: conn.connect(haproxy_stats_socket) conn.sendall(b'show stat\r\n') data = conn.recv(BUFFER_SIZE) while len(data) % BUFFER_SIZE == 0: try: data += conn.recv(BUFFER_SIZE, MSG_DONTWAIT) except socket.error: break return data finally: conn.close()
def __get_sock(self): if isinstance(self.__address, tuple): family = socket.AF_INET else: family = socket.AF_UNIX return socket.socket(family, socket.SOCK_STREAM)
def shutdown(self): if self.local_end_type in ConnectionBased: server_kill = self.socket_plinko(self.lhost,self.local_end_type) if server_kill.type != socket.AF_UNIX: server_kill.connect((self.lhost,self.lport)) server_kill.close() elif "unix" in self.local_end_type: try: remove(self.lhost) except: output("[?.?] Unable to delete Unix Socket: %s"%self.lhost,YELLOW) output("[^.^] Thanks for using Decept!") sys.exit()