【问题标题】:Ping to a specific IP address using python [duplicate]使用python Ping到特定的IP地址[重复]
【发布时间】:2014-09-15 07:21:38
【问题描述】:

我想编写一个 python 脚本来检查一个特定的 IP 地址是否可以访问。我是 python 编程的新手,不知道代码的外观。帮帮忙

【问题讨论】:

    标签: python network-programming ip-address ping icmp


    【解决方案1】:

    你可以这样试试;

    >>> import os
    >>> if os.system("ping -c 1 google.com") == 0:
    ...     print "host appears to be up"
    

    【讨论】:

    • 请注意,这不是跨平台的。
    【解决方案2】:

    您可以使用 subprocess 模块和 shlex 模块来解析 shell 命令,如下所示

    import shlex
    import subprocess
    
    # Tokenize the shell command
    # cmd will contain  ["ping","-c1","google.com"]     
    cmd=shlex.split("ping -c1 google.com")
    try:
       output = subprocess.check_output(cmd)
    except subprocess.CalledProcessError,e:
       #Will print the command failed with its exit status
       print "The IP {0} is NotReacahble".format(cmd[-1])
    else:
       print "The IP {0} is Reachable".format(cmd[-1])
    

    【讨论】:

    • 您能在这方面简要介绍一下“shlex”吗?另外,不使用 'shlex' 可以做到这一点吗?
    • @Goblin shlex.split() 在确定 args( 对于 unix shell) 的正确标记化时很有用,是的,它可以在没有 shlex 的情况下完成,在这种情况下你必须像 cmd 一样标记你的命令=["ping","-c1","google.com"] 作为列表并传递给 subprocess.check_ouptut 这项工作由 shlex.split() 为您完成。对于 shlex 参考阅读此链接docs.python.org/2/library/shlex.html
    • 知道了。非常感谢!
    • 可以使用rc = subprocess.call()的情况。如果是预期的,则无需引发异常。
    猜你喜欢
    • 2012-01-01
    • 1970-01-01
    • 2011-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-12
    • 1970-01-01
    • 2013-12-06
    相关资源
    最近更新 更多