猿问

如图所示,请帮忙写一个函数确定某个ip是否能ping通?

我的代码问题是,它另外弹出一个控制台,我想把这个黑框去掉,另一方面是不管是否ping通都返回true



慕娘9325324
浏览 174回答 2
2回答

阿晨1998

你这样直接使用os.system("ping")==0是不行的,执行ping命令后跟cmd执行一样,也会返回类似于ttl=245 time=36.798 ms这样的信息。所以你要做的是:在os.system("ping -n 1 "+ip)的返回结果中查找是否存在"TTL="这样的字符,如果存在表示ping通了,不存在就表示超时

拉莫斯之舞

def ping(host):    '''ping 1次指定地址'''    import subprocess,traceback, platform    if platform.system()=='Windows':        cmd = 'ping -n %d %s'%(1,host)    else:        cmd = 'ping -c %d %s'%(1,host)    try:        p = subprocess.Popen(args=cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)        (stdoutput,erroutput) = p.communicate()        # print stdoutput    except Exception, e:        traceback.print_exc()    if platform.system()=='Windows':        return stdoutput.find('Received = 1')>=0    else:        return stdoutput.find('1 packets received')>=0if __name__ == "__main__":    print ping('baidu.com')
随时随地看视频慕课网APP

相关分类

Python
我要回答