def connections(self, kind='inet'): if kind not in conn_tmap: raise ValueError("invalid %r kind argument; choose between %s" % (kind, ', '.join([repr(x) for x in conn_tmap]))) families, types = conn_tmap[kind] rawlist = cext.proc_connections(self.pid, families, types) # The underlying C implementation retrieves all OS connections # and filters them by PID. At this point we can't tell whether # an empty list means there were no connections for process or # process is no longer active so we force NSP in case the PID # is no longer there. if not rawlist: os.stat('/proc/%s' % self.pid) # will raise NSP if process is gone ret = [] for item in rawlist: fd, fam, type, laddr, raddr, status = item if fam not in families: continue if type not in types: continue status = TCP_STATUSES[status] nt = _common.pconn(fd, fam, type, laddr, raddr, status) ret.append(nt) # UNIX sockets if socket.AF_UNIX in families: ret.extend([_common.pconn(*conn) for conn in self._get_unix_sockets(self.pid)]) return ret
def process(file, family, type_): retlist = [] try: f = open(file, 'r') except IOError: # IPv6 not supported on this platform err = sys.exc_info()[1] if err.errno == errno.ENOENT and file.endswith('6'): return [] else: raise try: f.readline() # skip the first line for line in f: # IPv4 / IPv6 if family in (socket.AF_INET, socket.AF_INET6): _, laddr, raddr, status, _, _, _, _, _, inode = \ line.split()[:10] if inode in inodes: laddr = self._decode_address(laddr, family) raddr = self._decode_address(raddr, family) if type_ == socket.SOCK_STREAM: status = TCP_STATUSES[status] else: status = _common.CONN_NONE fd = int(inodes[inode]) conn = _common.pconn(fd, family, type_, laddr, raddr, status) retlist.append(conn) elif family == socket.AF_UNIX: tokens = line.split() _, _, _, _, type_, _, inode = tokens[0:7] if inode in inodes: if len(tokens) == 8: path = tokens[-1] else: path = "" fd = int(inodes[inode]) type_ = int(type_) conn = _common.pconn(fd, family, type_, path, None, _common.CONN_NONE) retlist.append(conn) else: raise ValueError(family) return retlist finally: f.close()
def process(file, family, type_): retlist = [] try: f = open(file, 'rt') except IOError: # IPv6 not supported on this platform err = sys.exc_info()[1] if err.errno == errno.ENOENT and file.endswith('6'): return [] else: raise try: f.readline() # skip the first line for line in f: # IPv4 / IPv6 if family in (socket.AF_INET, socket.AF_INET6): _, laddr, raddr, status, _, _, _, _, _, inode = \ line.split()[:10] if inode in inodes: laddr = self._decode_address(laddr, family) raddr = self._decode_address(raddr, family) if type_ == socket.SOCK_STREAM: status = TCP_STATUSES[status] else: status = _common.CONN_NONE fd = int(inodes[inode]) conn = _common.pconn(fd, family, type_, laddr, raddr, status) retlist.append(conn) elif family == socket.AF_UNIX: tokens = line.split() _, _, _, _, type_, _, inode = tokens[0:7] if inode in inodes: if len(tokens) == 8: path = tokens[-1] else: path = "" fd = int(inodes[inode]) type_ = int(type_) conn = _common.pconn(fd, family, type_, path, None, _common.CONN_NONE) retlist.append(conn) else: raise ValueError(family) return retlist finally: f.close()
def net_connections(kind, _pid=-1): """Return socket connections. If pid == -1 return system-wide connections (as opposed to connections opened by one process only). Only INET sockets are returned (UNIX are not). """ cmap = _common.conn_tmap.copy() if _pid == -1: cmap.pop('unix', 0) if kind not in cmap: raise ValueError("invalid %r kind argument; choose between %s" % (kind, ', '.join([repr(x) for x in cmap]))) families, types = _common.conn_tmap[kind] rawlist = cext.net_connections(_pid, families, types) ret = [] for item in rawlist: fd, fam, type_, laddr, raddr, status, pid = item if fam not in families: continue if type_ not in types: continue status = TCP_STATUSES[status] if _pid == -1: nt = _common.sconn(fd, fam, type_, laddr, raddr, status, pid) else: nt = _common.pconn(fd, fam, type_, laddr, raddr, status) ret.append(nt) return ret
def retrieve(self, kind, pid=None): if kind not in self.tmap: raise ValueError("invalid %r kind argument; choose between %s" % (kind, ', '.join([repr(x) for x in self.tmap]))) if pid is not None: inodes = self.get_proc_inodes(pid) if not inodes: # no connections for this process return [] else: inodes = self.get_all_inodes() ret = [] for f, family, type_ in self.tmap[kind]: if family in (socket.AF_INET, socket.AF_INET6): ls = self.process_inet( "/proc/net/%s" % f, family, type_, inodes, filter_pid=pid) else: ls = self.process_unix( "/proc/net/%s" % f, family, inodes, filter_pid=pid) for fd, family, type_, laddr, raddr, status, bound_pid in ls: if pid: conn = _common.pconn(fd, family, type_, laddr, raddr, status) else: conn = _common.sconn(fd, family, type_, laddr, raddr, status, bound_pid) ret.append(conn) return ret
def retrieve(self, kind, pid=None): if kind not in self.tmap: raise ValueError("invalid %r kind argument; choose between %s" % (kind, ', '.join([repr(x) for x in self.tmap]))) if pid is not None: inodes = self.get_proc_inodes(pid) if not inodes: # no connections for this process return [] else: inodes = self.get_all_inodes() ret = [] for f, family, type_ in self.tmap[kind]: if family in (socket.AF_INET, socket.AF_INET6): ls = self.process_inet("/proc/net/%s" % f, family, type_, inodes, filter_pid=pid) else: ls = self.process_unix("/proc/net/%s" % f, family, inodes, filter_pid=pid) for fd, family, type_, laddr, raddr, status, bound_pid in ls: if pid: conn = _common.pconn(fd, family, type_, laddr, raddr, status) else: conn = _common.sconn(fd, family, type_, laddr, raddr, status, bound_pid) ret.append(conn) return ret
def connections(self, kind='inet'): if kind not in conn_tmap: raise ValueError("invalid %r kind argument; choose between %s" % (kind, ', '.join([repr(x) for x in conn_tmap]))) families, types = conn_tmap[kind] rawlist = cext.proc_connections(self.pid, families, types) ret = [] for item in rawlist: fd, fam, type, laddr, raddr, status = item status = TCP_STATUSES[status] nt = _common.pconn(fd, fam, type, laddr, raddr, status) ret.append(nt) return ret
def connections(self, kind='inet'): ret = net_connections(kind, _pid=self.pid) # The underlying C implementation retrieves all OS connections # and filters them by PID. At this point we can't tell whether # an empty list means there were no connections for process or # process is no longer active so we force NSP in case the PID # is no longer there. if not ret: os.stat('/proc/%s' % self.pid) # will raise NSP if process is gone # UNIX sockets if kind in ('all', 'unix'): ret.extend([_common.pconn(*conn) for conn in self._get_unix_sockets(self.pid)]) return ret
def connections(self, kind='inet'): ret = net_connections(kind, _pid=self.pid) # The underlying C implementation retrieves all OS connections # and filters them by PID. At this point we can't tell whether # an empty list means there were no connections for process or # process is no longer active so we force NSP in case the PID # is no longer there. if not ret: os.stat('/proc/%s' % self.pid) # will raise NSP if process is gone # UNIX sockets if kind in ('all', 'unix'): ret.extend([ _common.pconn(*conn) for conn in self._get_unix_sockets(self.pid) ]) return ret
def parse_connections(conns): if not conns: return conns connections = [] for conn in conns: laddr = raddr = None if conn[3]: laddr = dict(addr(*conn[3])._asdict()) if conn[4]: raddr = dict(addr(*conn[4])._asdict()) connection_dict = dict(pconn(conn[0], conn[1], conn[2], laddr, raddr, conn[5])._asdict()) # print(connection_dict, file=sys.stderr) connections.append(connection_dict) return connections
def net_connections(kind, _pid=-1): """Return socket connections. If pid == -1 return system-wide connections (as opposed to connections opened by one process only). """ if kind not in conn_tmap: raise ValueError("invalid %r kind argument; choose between %s" % (kind, ', '.join([repr(x) for x in conn_tmap]))) families, types = conn_tmap[kind] rawlist = cext.net_connections(_pid, families, types) ret = [] for item in rawlist: fd, fam, type, laddr, raddr, status, pid = item status = TCP_STATUSES[status] if _pid == -1: nt = _common.sconn(fd, fam, type, laddr, raddr, status, pid) else: nt = _common.pconn(fd, fam, type, laddr, raddr, status) ret.append(nt) return ret
def compare_procsys_connections(self, pid, proc_cons, kind='all'): """Given a process PID and its list of connections compare those against system-wide connections retrieved via psutil.net_connections. """ try: sys_cons = psutil.net_connections(kind=kind) except psutil.AccessDenied: # On OSX, system-wide connections are retrieved by iterating # over all processes if OSX: return else: raise # Filter for this proc PID and exlucde PIDs from the tuple. sys_cons = [c[:-1] for c in sys_cons if c.pid == pid] if FREEBSD: # On FreeBSD all fds are set to -1 so exclude them # from comparison. proc_cons = [pconn(*[-1] + list(x[1:])) for x in proc_cons] sys_cons.sort() proc_cons.sort() self.assertEqual(proc_cons, sys_cons)
def compare_procsys_connections(pid, proc_cons, kind='all'): """Given a process PID and its list of connections compare those against system-wide connections retrieved via psutil.net_connections. """ from psutil._common import pconn try: sys_cons = psutil.net_connections(kind=kind) except psutil.AccessDenied: # On OSX, system-wide connections are retrieved by iterating # over all processes if OSX: return else: raise # exclude PIDs from syscons sys_cons = [c[:-1] for c in sys_cons if c.pid == pid] if FREEBSD: # On FreeBSD all fds are set to -1 so exclude them # for comparison. proc_cons = [pconn(*[-1] + list(x[1:])) for x in proc_cons] proc_cons.sort() sys_cons.sort() assert proc_cons == sys_cons, (proc_cons, sys_cons)