python判断IP地址是否在线

判断IP地址是否在线
以百度(www.baidu.com)为例 代码如下:

import os
import platform


def decide_server():
    # 获取操作系统
    sys = platform.system()
    # IP地址
    IP = "www.baidu.com"
    print(sys)

    if sys == "Windows":
        # 打开一个管道ping IP地址
        visit_IP = os.popen('ping %s' % IP)
        # 读取结果
        result = visit_IP.read()
        # 关闭os.popen()
        visit_IP.close()
        # 判断IP是否在线
        if 'TTL' in result:
            print('服务器 在线')
        else:
            print('服务器 不在线')
    elif sys == "Linux":
        visit_IP = os.popen('ping -c 1 %s' % IP)
        result = visit_IP.read()
        visit_IP.close()
        if 'ttl' in result:
            print('服务器 在线')
        else:
            print('服务器 不在线')
    else:
        print("Error")

判断操作系统是因为各个操作系统的返回值不同
例如:
Linux

PING www.a.shifen.com (110.242.68.4) 56(84) bytes of data.
64 bytes from 110.242.68.4 (110.242.68.4): icmp_seq=1 ttl=53 time=10.8 ms

--- www.a.shifen.com ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 10.871/10.871/10.871/0.000 ms

Windows

正在 Ping www.a.shifen.com [110.242.68.4] 具有 32 字节的数据:
来自 110.242.68.4 的回复: 字节=32 时间=11ms TTL=53
来自 110.242.68.4 的回复: 字节=32 时间=11ms TTL=53
来自 110.242.68.4 的回复: 字节=32 时间=10ms TTL=53
来自 110.242.68.4 的回复: 字节=32 时间=11ms TTL=53

110.242.68.4 的 Ping 统计信息:
    数据包: 已发送 = 4,已接收 = 4,丢失 = 0 (0% 丢失),
往返行程的估计时间(以毫秒为单位):
    最短 = 10ms,最长 = 11ms,平均 = 10ms

总结

工作随笔,希望可以帮助到大家!

猜你喜欢

转载自blog.csdn.net/black_lightning/article/details/112210107