#!/usr/bin/python3

# -*- coding:utf8 -*-

#!/usr/bin/python

import subprocess    

import re

def LinkState(ip):

    return getLinkState(ip)

# 获取链路状态

def getLinkState(ip):

    #运行ping程序

    p = subprocess.Popen(["ping.exe", ip], 

            stdin = subprocess.PIPE, 

            stdout = subprocess.PIPE, 

            stderr = subprocess.PIPE, 

            shell = True)  

    #得到ping的结果

    out = p.stdout.read()  

    #找出丢包率,这里通过‘%’匹配

    regex = re.compile(r'\w*%\w*')

    packetLossRateList = regex.findall(str(out))

    packetLossRate = packetLossRateList[0]

    if packetLossRate == "0%":

        print(packetLossRate)

        return 1

    else:

        return 0

if __name__ == '__main__':

    ip = '192.168.0.100'    #要ping的主机

    while True:

        if LinkState(ip) == 1:

            print("connected")

            break

        else:

            print("not connected")

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐