當前位置: 首頁>>代碼示例>>Python>>正文


Python psutil.net_connections方法代碼示例

本文整理匯總了Python中psutil.net_connections方法的典型用法代碼示例。如果您正苦於以下問題:Python psutil.net_connections方法的具體用法?Python psutil.net_connections怎麽用?Python psutil.net_connections使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在psutil的用法示例。


在下文中一共展示了psutil.net_connections方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: compare_procsys_connections

# 需要導入模塊: import psutil [as 別名]
# 或者: from psutil import net_connections [as 別名]
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) 
開發者ID:giampaolo,項目名稱:psutil,代碼行數:21,代碼來源:test_connections.py

示例2: get_next_port

# 需要導入模塊: import psutil [as 別名]
# 或者: from psutil import net_connections [as 別名]
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.') 
開發者ID:mars-project,項目名稱:mars,代碼行數:23,代碼來源:utils.py

示例3: compare_procsys_connections

# 需要導入模塊: import psutil [as 別名]
# 或者: from psutil import net_connections [as 別名]
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
# ===================================================================== 
開發者ID:birforce,項目名稱:vnpy_crypto,代碼行數:26,代碼來源:test_connections.py

示例4: test_it

# 需要導入模塊: import psutil [as 別名]
# 或者: from psutil import net_connections [as 別名]
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='???') 
開發者ID:birforce,項目名稱:vnpy_crypto,代碼行數:23,代碼來源:test_connections.py

示例5: test_net_connections

# 需要導入模塊: import psutil [as 別名]
# 或者: from psutil import net_connections [as 別名]
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) 
開發者ID:birforce,項目名稱:vnpy_crypto,代碼行數:25,代碼來源:test_unicode.py

示例6: test_net_connections_mocked

# 需要導入模塊: import psutil [as 別名]
# 或者: from psutil import net_connections [as 別名]
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
# ===================================================================== 
開發者ID:birforce,項目名稱:vnpy_crypto,代碼行數:18,代碼來源:test_linux.py

示例7: test_procfs_path

# 需要導入模塊: import psutil [as 別名]
# 或者: from psutil import net_connections [as 別名]
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) 
開發者ID:birforce,項目名稱:vnpy_crypto,代碼行數:20,代碼來源:test_linux.py

示例8: search

# 需要導入模塊: import psutil [as 別名]
# 或者: from psutil import net_connections [as 別名]
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 
開發者ID:oooldtoy,項目名稱:SSTAP_ip_crawl_tool,代碼行數:19,代碼來源:ip_crawl_tool.py

示例9: test_net_connections

# 需要導入模塊: import psutil [as 別名]
# 或者: from psutil import net_connections [as 別名]
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) 
開發者ID:giampaolo,項目名稱:psutil,代碼行數:24,代碼來源:test_unicode.py

示例10: test_emulate_unix

# 需要導入模塊: import psutil [as 別名]
# 或者: from psutil import net_connections [as 別名]
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
# ===================================================================== 
開發者ID:giampaolo,項目名稱:psutil,代碼行數:18,代碼來源:test_linux.py

示例11: main

# 需要導入模塊: import psutil [as 別名]
# 或者: from psutil import net_connections [as 別名]
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],
        )) 
開發者ID:giampaolo,項目名稱:psutil,代碼行數:23,代碼來源:netstat.py

示例12: check

# 需要導入模塊: import psutil [as 別名]
# 或者: from psutil import net_connections [as 別名]
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 
開發者ID:languitar,項目名稱:autosuspend,代碼行數:21,代碼來源:activity.py

示例13: netstat_scan

# 需要導入模塊: import psutil [as 別名]
# 或者: from psutil import net_connections [as 別名]
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]
    ) 
開發者ID:WoTTsecurity,項目名稱:agent,代碼行數:25,代碼來源:security_helper.py

示例14: histmain

# 需要導入模塊: import psutil [as 別名]
# 或者: from psutil import net_connections [as 別名]
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 
開發者ID:vesche,項目名稱:histstat,代碼行數:21,代碼來源:histstat.py

示例15: get_connections

# 需要導入模塊: import psutil [as 別名]
# 或者: from psutil import net_connections [as 別名]
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 
開發者ID:Jahaja,項目名稱:psdash,代碼行數:26,代碼來源:node.py


注:本文中的psutil.net_connections方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。