简体   繁体   English

使用 Python 检查来自 IP 地址的网络连接

[英]Check network connection from an IP address with Python

如何使用 python 检查是否仍有来自特定 IP 地址的连接。

As far as I understood the OP is looking for active connection FROM certain ip, meaning he wants to check locally if there is active connection exists. 据我了解,OP正在某些ip寻找活动连接,这意味着他想在本地检查是否存在活动连接。 It looks like something along lines of netstat to me. 在我看来,这就像netstat一样。 There are several options: 有几种选择:

  1. You can use psutils as demonstrated in this post. 您可以使用的PSUtils作为证明这个岗位。 You will want to cycle the active processes and query active connections. 您将要循环活动的进程并查询活动的连接。

  2. You could use netstat.py - a clone of netstat by Jay Loden, Giampaolo Rodola' to do the job for you. 您可以使用netstat.py -Gistataolo Rodola的Jay Loden的netstat副本为您完成工作。

Added : 新增

You can do something like that: 您可以执行以下操作:

import psutil

def remote_ips():
    '''
    Returns the list of IPs for current active connections

    '''

    remote_ips = []

    for process in psutil.process_iter():
        try:
            connections = process.get_connections(kind='inet')
        except psutil.AccessDenied or psutil.NoSuchProcess:
            pass
        else:
            for connection in connections:
                if connection.remote_address and connection.remote_address[0] not in remote_ips:
                    remote_ips.append(connection.remote_address[0])

    return remote_ips

def remote_ip_present(ip):
    return ip in remote_ips()

This is how it works: 它是这样工作的:

>>>remote_ips()
['192.168.1.50', '192.168.1.15', '192.168.1.52', '198.252.206.16', '198.252.206.17'] 
>>>remote_ip_present('192.168.1.52')
True
>>>remote_ip_present('10.1.1.1')
False

ping the ip address ping IP地址

import os
#192.168.1.10 is the ip address
ret = os.system("ping -o -c 3 -W 3000 192.168.1.10")
if ret != 0:
    print "pc still alive"

well in any case you really want to check for availability of incoming connection on the PC you are trying to connect you need to make a program that will receive the connection which is already out of the question. 在任何情况下,如果您真的想在尝试连接的PC上检查传入连接的可用性,都需要制作一个程序来接收已经不存在的连接。

You can use socket library : 您可以使用套接字库

import socket

try:
    socket.gethostbyaddr(your_ip_adrress)
except socket.herror:
    print u"Unknown host"

if you are on Windows:如果您在 Windows 上:

import os
ret = os.system("ping -n 3 1.1.1.1")
if ret != 0:
     print("Ip address responding")

The -n argument is for how many times to ping it -n 参数是多少次 ping 它

if you are on LInux:如果你在 LLinux 上:

import os
ret = os.system("ping -c 3 1.1.1.1")
if ret != 0:
     print("Ip address responding")
import os
address = "my_ip_address"
os.system('ping ' + address)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM