OSコマンドとして実行。

  • 配列に指定した複数ホストに対してPingを実行
  • Pingに成功した場合はホスト名を、失敗した場合はホストとエラーメッセージを出力
#!/usr/bin/python
# vim: fileencoding=utf-8

import subprocess

class Ping(object):
    def __init__(self, hosts):
        for host in hosts:
            ping = subprocess.Popen(
                ["ping", "-c", "1", host],
                stdout = subprocess.PIPE,
                stderr = subprocess.PIPE
            )
            out, error = ping.communicate()
            if error:
                print('[NG]: ' + 'ServerName->' + host + ', Msg->\'' + error.rstrip() + '\'')
            else:
                print('[OK]: ' + 'ServerName->' + host)


if __name__ == '__main__':
    hosts = [
        'www.google.com',
        'www.yahoo.com',
        'www.hogehage.com',
       ]
    Ping(hosts)


実行結果

$ sudo python /tmp/pingtest.py 
[OK]: ServerName->www.google.com
[OK]: ServerName->www.yahoo.com
[NG]: ServerName->www.hogehage.com, Msg->'ping: unknown host www.hogehage.com'