当前位置: 首页>>代码示例>>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;未经允许,请勿转载。