Python psutil.net_connections() Examples

The following are 30 code examples of psutil.net_connections(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module psutil , or try the search function .
Example #1
Source File: test_connections.py    From psutil with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
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 MACOS, system-wide connections are retrieved by iterating
            # over all processes
            if MACOS:
                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]
        sys_cons.sort()
        proc_cons.sort()
        self.assertEqual(proc_cons, sys_cons) 
Example #2
Source File: ajax.py    From BaoTa-Panel with GNU General Public License v3.0 6 votes vote down vote up
def GetNetWorkList(self,get):
        import psutil
        netstats = psutil.net_connections()
        networkList = []
        for netstat in netstats:
            tmp = {}
            if netstat.type == 1:
                tmp['type'] = 'tcp'
            else:
                tmp['type'] = 'udp'
            tmp['family']   = netstat.family
            tmp['laddr']    = netstat.laddr
            tmp['raddr']    = netstat.raddr
            tmp['status']   = netstat.status
            p = psutil.Process(netstat.pid)
            tmp['process']  = p.name()
            tmp['pid']      = netstat.pid
            networkList.append(tmp)
            del(p)
            del(tmp)
        networkList = sorted(networkList, key=lambda x : x['status'], reverse=True);
        return networkList;
    
    #取进程列表 
Example #3
Source File: activity.py    From autosuspend with GNU General Public License v2.0 6 votes vote down vote up
def check(self) -> Optional[str]:
        own_addresses = [
            (item.family, item.address.split("%")[0])
            for sublist in psutil.net_if_addrs().values()
            for item in sublist
        ]
        connected = [
            c.laddr[1]
            for c in psutil.net_connections()
            if (
                (c.family, c.laddr[0]) in own_addresses
                and c.status == "ESTABLISHED"
                and c.laddr[1] in self._ports
            )
        ]
        if connected:
            return "Ports {} are connected".format(connected)
        else:
            return None 
Example #4
Source File: security_helper.py    From agent with MIT License 6 votes vote down vote up
def netstat_scan():
    """
    Returns all open inet connections with their addresses and PIDs.
    """
    connections = psutil.net_connections(kind='inet')
    return (
        [{
            'ip_version': 4 if c.family == socket.AF_INET else 6,
            'type': 'udp' if c.type == socket.SOCK_DGRAM else 'tcp',
            'local_address': c.laddr,
            'remote_address': c.raddr,
            'status': c.status if c.type == socket.SOCK_STREAM else None,
            'pid': c.pid
        } for c in connections if c.raddr],
        [{
            'ip_version': 4 if c.family == socket.AF_INET else 6,
            'host': c.laddr[0],
            'port': c.laddr[1],
            'proto': {SocketKind.SOCK_STREAM: 'tcp', SocketKind.SOCK_DGRAM: 'udp'}.get(c.type),
            'state': c.status if c.type == socket.SOCK_STREAM else None,
            'pid': c.pid
        } for c in connections if not c.raddr and c.laddr]
    ) 
Example #5
Source File: netstat.py    From psutil with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def main():
    templ = "%-5s %-30s %-30s %-13s %-6s %s"
    print(templ % (
        "Proto", "Local address", "Remote address", "Status", "PID",
        "Program name"))
    proc_names = {}
    for p in psutil.process_iter(['pid', 'name']):
        proc_names[p.info['pid']] = p.info['name']
    for c in psutil.net_connections(kind='inet'):
        laddr = "%s:%s" % (c.laddr)
        raddr = ""
        if c.raddr:
            raddr = "%s:%s" % (c.raddr)
        print(templ % (
            proto_map[(c.family, c.type)],
            laddr,
            raddr or AD,
            c.status,
            c.pid or AD,
            proc_names.get(c.pid, '?')[:15],
        )) 
Example #6
Source File: test_linux.py    From psutil with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_emulate_unix(self):
        with mock_open_content(
            '/proc/net/unix',
            textwrap.dedent("""\
                0: 00000003 000 000 0001 03 462170 @/tmp/dbus-Qw2hMPIU3n
                0: 00000003 000 000 0001 03 35010 @/tmp/dbus-tB2X8h69BQ
                0: 00000003 000 000 0001 03 34424 @/tmp/dbus-cHy80Y8O
                000000000000000000000000000000000000000000000000000000
                """)) as m:
            psutil.net_connections(kind='unix')
            assert m.called


# =====================================================================
# --- system disks
# ===================================================================== 
Example #7
Source File: histstat.py    From histstat with MIT License 6 votes vote down vote up
def histmain(interval):
    """Primary execution function for histstat."""

    # ladies and gentlemen this is your captain speaking
    output.preflight()

    # get initial connections
    connections_A = psutil.net_connections()
    for c in connections_A:
        output.process(process_conn(c))

    # primary loop
    while True:
        time.sleep(interval)
        connections_B = psutil.net_connections()
        for c in connections_B:
            if c not in connections_A:
                output.process(process_conn(c))
        connections_A = connections_B 
Example #8
Source File: node.py    From psdash with Creative Commons Zero v1.0 Universal 6 votes vote down vote up
def get_connections(self, filters=None):
        filters = filters or {}
        connections = []

        for c in psutil.net_connections('all'):
            conn = {
                'fd': c.fd,
                'pid': c.pid,
                'family': socket_families[c.family],
                'type': socket_types[c.type],
                'local_addr_host': c.laddr[0] if c.laddr else None,
                'local_addr_port': c.laddr[1] if c.laddr else None,
                'remote_addr_host': c.raddr[0] if c.raddr else None,
                'remote_addr_port': c.raddr[1] if c.raddr else None,
                'state': c.status
            }

            for k, v in filters.iteritems():
                if v and conn.get(k) != v:
                    break
            else:
                connections.append(conn)

        return connections 
Example #9
Source File: test_unicode.py    From psutil with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_net_connections(self):
        def find_sock(cons):
            for conn in cons:
                if os.path.basename(conn.laddr).startswith(TESTFN_PREFIX):
                    return conn
            raise ValueError("connection not found")

        name = self.get_testfn(suffix=self.funky_suffix)
        try:
            sock = bind_unix_socket(name)
        except UnicodeEncodeError:
            if PY3:
                raise
            else:
                raise unittest.SkipTest("not supported")
        with closing(sock):
            cons = psutil.net_connections(kind='unix')
            # AF_UNIX addr not set on OpenBSD
            if not OPENBSD:
                conn = find_sock(cons)
                self.assertIsInstance(conn.laddr, str)
                self.assertEqual(conn.laddr, name) 
Example #10
Source File: test_connections.py    From jarvis with GNU General Public License v2.0 6 votes vote down vote up
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]
        sys_cons.sort()
        proc_cons.sort()
        self.assertEqual(proc_cons, sys_cons)


# =====================================================================
# --- Test unconnected sockets
# ===================================================================== 
Example #11
Source File: test_connections.py    From jarvis with GNU General Public License v2.0 6 votes vote down vote up
def test_it(self):
        def check(cons, families, types_):
            AF_UNIX = getattr(socket, 'AF_UNIX', object())
            for conn in cons:
                self.assertIn(conn.family, families, msg=conn)
                if conn.family != AF_UNIX:
                    self.assertIn(conn.type, types_, msg=conn)
                check_connection_ntuple(conn)

        with create_sockets():
            from psutil._common import conn_tmap
            for kind, groups in conn_tmap.items():
                # XXX: SunOS does not retrieve UNIX sockets.
                if kind == 'unix' and not HAS_CONNECTIONS_UNIX:
                    continue
                families, types_ = groups
                cons = psutil.net_connections(kind)
                self.assertEqual(len(cons), len(set(cons)))
                check(cons, families, types_)

            self.assertRaises(ValueError, psutil.net_connections, kind='???') 
Example #12
Source File: ip_crawl_tool.py    From SSTAP_ip_crawl_tool with GNU General Public License v3.0 6 votes vote down vote up
def search(name):
    ip_temp = []
    for conn in net_connections('all'):
        laddr, raddr, status, pid = conn[3:]
        if not raddr:
            continue
        try:
            filename = basename(Process(pid).exe())
        except:
            pass
        else:
            if filename == name:
                #print('远程地址:'+str(raddr))
                if raddr.ip != '127.0.0.1' and ':' not in raddr.ip:#判断是否为本机地址以及剔除ipv6
                    if is_internal_ip(raddr.ip) != True:#判断是否为内网ip
                        ip_temp.append(raddr.ip)
    return ip_temp 
Example #13
Source File: test_unicode.py    From jarvis with GNU General Public License v2.0 6 votes vote down vote up
def test_net_connections(self):
        def find_sock(cons):
            for conn in cons:
                if os.path.basename(conn.laddr).startswith(TESTFILE_PREFIX):
                    return conn
            raise ValueError("connection not found")

        suffix = os.path.basename(self.funky_name)
        with unix_socket_path(suffix=suffix) as name:
            try:
                sock = bind_unix_socket(name)
            except UnicodeEncodeError:
                if PY3:
                    raise
                else:
                    raise unittest.SkipTest("not supported")
            with closing(sock):
                cons = psutil.net_connections(kind='unix')
                # AF_UNIX addr not set on OpenBSD
                if not OPENBSD:
                    conn = find_sock(cons)
                    self.assertIsInstance(conn.laddr, str)
                    self.assertEqual(conn.laddr, name) 
Example #14
Source File: test_linux.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def test_net_connections_mocked(self):
        with mock_open_content(
            '/proc/net/unix',
            textwrap.dedent("""\
                0: 00000003 000 000 0001 03 462170 @/tmp/dbus-Qw2hMPIU3n
                0: 00000003 000 000 0001 03 35010 @/tmp/dbus-tB2X8h69BQ
                0: 00000003 000 000 0001 03 34424 @/tmp/dbus-cHy80Y8O
                000000000000000000000000000000000000000000000000000000
                """)) as m:
            psutil.net_connections(kind='unix')
            assert m.called


# =====================================================================
# --- system disk
# ===================================================================== 
Example #15
Source File: utils.py    From mars with Apache License 2.0 6 votes vote down vote up
def get_next_port(typ=None):
    import psutil
    try:
        conns = psutil.net_connections()
        typ = typ or socket.SOCK_STREAM
        occupied = set(sc.laddr.port for sc in conns
                       if sc.type == typ and LOW_PORT_BOUND <= sc.laddr.port <= HIGH_PORT_BOUND)
    except psutil.AccessDenied:
        occupied = _get_ports_from_netstat()

    occupied.update(_local_occupied_ports)
    randn = struct.unpack('<Q', os.urandom(8))[0]
    idx = int(randn % (1 + HIGH_PORT_BOUND - LOW_PORT_BOUND - len(occupied)))
    for i in range(LOW_PORT_BOUND, HIGH_PORT_BOUND + 1):
        if i in occupied:
            continue
        if idx == 0:
            _local_occupied_ports.add(i)
            return i
        idx -= 1
    raise SystemError('No ports available.') 
Example #16
Source File: network.py    From integrations-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _cx_state_psutil(self, tags=None):
        """
        Collect metrics about connections state using psutil
        """
        metrics = defaultdict(int)
        tags = [] if tags is None else tags
        for conn in psutil.net_connections():
            protocol = self._parse_protocol_psutil(conn)
            status = self.tcp_states['psutil'].get(conn.status)
            metric = self.cx_state_gauge.get((protocol, status))
            if metric is None:
                self.log.warning('Metric not found for: %s,%s', protocol, status)
            else:
                metrics[metric] += 1

        for metric, value in iteritems(metrics):
            self.gauge(metric, value, tags=tags) 
Example #17
Source File: fc_env.py    From gymfc with MIT License 6 votes vote down vote up
def _get_open_port(self, start_port):
        """ Return an available open port, starting from start_port

        Args:
            start_port (int): first port to try, will increment until port is open
        """
         
        connections = psutil.net_connections()
        open_ports = []
        for c in connections:
            open_ports.append(c.laddr.port)
        for port in range(start_port, 2**16):
            if not (port in open_ports):
                return port

        raise Exception("Could not find an open port") 
Example #18
Source File: test_linux.py    From jarvis with GNU General Public License v2.0 6 votes vote down vote up
def test_procfs_path(self):
        tdir = tempfile.mkdtemp()
        try:
            psutil.PROCFS_PATH = tdir
            self.assertRaises(IOError, psutil.virtual_memory)
            self.assertRaises(IOError, psutil.cpu_times)
            self.assertRaises(IOError, psutil.cpu_times, percpu=True)
            self.assertRaises(IOError, psutil.boot_time)
            # self.assertRaises(IOError, psutil.pids)
            self.assertRaises(IOError, psutil.net_connections)
            self.assertRaises(IOError, psutil.net_io_counters)
            self.assertRaises(IOError, psutil.net_if_stats)
            self.assertRaises(IOError, psutil.disk_io_counters)
            self.assertRaises(IOError, psutil.disk_partitions)
            self.assertRaises(psutil.NoSuchProcess, psutil.Process)
        finally:
            psutil.PROCFS_PATH = "/proc"
            os.rmdir(tdir) 
Example #19
Source File: test_connections.py    From vnpy_crypto with MIT License 6 votes vote down vote up
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]
        sys_cons.sort()
        proc_cons.sort()
        self.assertEqual(proc_cons, sys_cons)


# =====================================================================
# --- Test unconnected sockets
# ===================================================================== 
Example #20
Source File: test_connections.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def test_it(self):
        def check(cons, families, types_):
            AF_UNIX = getattr(socket, 'AF_UNIX', object())
            for conn in cons:
                self.assertIn(conn.family, families, msg=conn)
                if conn.family != AF_UNIX:
                    self.assertIn(conn.type, types_, msg=conn)
                check_connection_ntuple(conn)

        with create_sockets():
            from psutil._common import conn_tmap
            for kind, groups in conn_tmap.items():
                # XXX: SunOS does not retrieve UNIX sockets.
                if kind == 'unix' and not HAS_CONNECTIONS_UNIX:
                    continue
                families, types_ = groups
                cons = psutil.net_connections(kind)
                self.assertEqual(len(cons), len(set(cons)))
                check(cons, families, types_)

            self.assertRaises(ValueError, psutil.net_connections, kind='???') 
Example #21
Source File: test_linux.py    From jarvis with GNU General Public License v2.0 6 votes vote down vote up
def test_net_connections_mocked(self):
        def open_mock(name, *args, **kwargs):
            if name == '/proc/net/unix':
                return io.StringIO(textwrap.dedent(u"""\
                    0: 00000003 000 000 0001 03 462170 @/tmp/dbus-Qw2hMPIU3n
                    0: 00000003 000 000 0001 03 35010 @/tmp/dbus-tB2X8h69BQ
                    0: 00000003 000 000 0001 03 34424 @/tmp/dbus-cHy80Y8O
                    000000000000000000000000000000000000000000000000000000
                    """))
            else:
                return orig_open(name, *args, **kwargs)

        orig_open = open
        patch_point = 'builtins.open' if PY3 else '__builtin__.open'
        with mock.patch(patch_point, side_effect=open_mock) as m:
            psutil.net_connections(kind='unix')
            assert m.called


# =====================================================================
# --- system disk
# ===================================================================== 
Example #22
Source File: test_unicode.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def test_net_connections(self):
        def find_sock(cons):
            for conn in cons:
                if os.path.basename(conn.laddr).startswith(TESTFILE_PREFIX):
                    return conn
            raise ValueError("connection not found")

        suffix = os.path.basename(self.funky_name)
        with unix_socket_path(suffix=suffix) as name:
            try:
                sock = bind_unix_socket(name)
            except UnicodeEncodeError:
                if PY3:
                    raise
                else:
                    raise unittest.SkipTest("not supported")
            with closing(sock):
                cons = psutil.net_connections(kind='unix')
                # AF_UNIX addr not set on OpenBSD
                if not OPENBSD:
                    conn = find_sock(cons)
                    self.assertIsInstance(conn.laddr, str)
                    self.assertEqual(conn.laddr, name) 
Example #23
Source File: test_linux.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def test_procfs_path(self):
        tdir = tempfile.mkdtemp()
        try:
            psutil.PROCFS_PATH = tdir
            self.assertRaises(IOError, psutil.virtual_memory)
            self.assertRaises(IOError, psutil.cpu_times)
            self.assertRaises(IOError, psutil.cpu_times, percpu=True)
            self.assertRaises(IOError, psutil.boot_time)
            # self.assertRaises(IOError, psutil.pids)
            self.assertRaises(IOError, psutil.net_connections)
            self.assertRaises(IOError, psutil.net_io_counters)
            self.assertRaises(IOError, psutil.net_if_stats)
            self.assertRaises(IOError, psutil.disk_io_counters)
            self.assertRaises(IOError, psutil.disk_partitions)
            self.assertRaises(psutil.NoSuchProcess, psutil.Process)
        finally:
            psutil.PROCFS_PATH = "/proc"
            os.rmdir(tdir) 
Example #24
Source File: test_memory_leaks.py    From jarvis with GNU General Public License v2.0 5 votes vote down vote up
def test_net_connections(self):
        with create_sockets():
            self.execute(psutil.net_connections) 
Example #25
Source File: test_contracts.py    From jarvis with GNU General Public License v2.0 5 votes vote down vote up
def test_net_connections(self):
        with unix_socket_path() as name:
            with closing(bind_unix_socket(name)):
                cons = psutil.net_connections(kind='unix')
                assert cons
                for conn in cons:
                    self.assertIsInstance(conn.laddr, str) 
Example #26
Source File: test_linux.py    From jarvis with GNU General Public License v2.0 5 votes vote down vote up
def test_net_connections_ipv6_unsupported(self, supports_ipv6, inet_ntop):
        # see: https://github.com/giampaolo/psutil/issues/623
        try:
            s = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
            self.addCleanup(s.close)
            s.bind(("::1", 0))
        except socket.error:
            pass
        psutil.net_connections(kind='inet6') 
Example #27
Source File: test_connections.py    From jarvis with GNU General Public License v2.0 5 votes vote down vote up
def test_multi_socks(self):
        with create_sockets() as socks:
            cons = [x for x in psutil.net_connections(kind='all')
                    if x.pid == os.getpid()]
            self.assertEqual(len(cons), len(socks)) 
Example #28
Source File: common.py    From minos with MIT License 5 votes vote down vote up
def get_random_port():
    rand = random.Random()
    while True:
        port = rand.randint(10000, 60000)
        my_os = platform.system()
        if 'Darwin' in my_os:  # checking open ports with psutil on Mac requires root!
            return port
        used_ports = [x.laddr[1] for x in psutil.net_connections()]
        if port not in used_ports:
            return port 
Example #29
Source File: testtools.py    From flocker with Apache License 2.0 5 votes vote down vote up
def _find_process_name(port_number):
    """
    Get the name of the process using the given port number.
    """
    for connection in psutil.net_connections():
        if connection.laddr[1] == port_number:
            return psutil.Process(connection.pid).name()
    return None 
Example #30
Source File: PORT.py    From AIOPS_PLATFORM with MIT License 5 votes vote down vote up
def getPortInfo(self):
        result = []
        AF_INET6 = getattr(socket, 'AF_INET6', object())
        type_map = {
            (AF_INET, SOCK_STREAM): 'TCP',
            (AF_INET6, SOCK_STREAM): 'TCP6',
            (AF_INET, SOCK_DGRAM): 'UDP',
            (AF_INET6, SOCK_DGRAM): 'UDP6',
        }
        netproc = psutil.net_connections()
        for n in netproc:
            pid = ''
            raddr_ip = ''
            raddr_port = ''
            type_val = type_map[(n.family, n.type)]
            laddr_ip = n.laddr[0]
            laddr_port = n.laddr[1]
            status = n.status
            pid = n.pid
            if len(n.raddr) > 0:
                raddr_ip = n.raddr[0]
                raddr_port = n.raddr[1]

            result.append([type_val, status, [laddr_ip], laddr_port, raddr_ip, raddr_port, pid])
        return(result)

    ## get Proc Info