Pythonで、ICMPでサーバーにpingを行い、サーバーからの応答があればTRUE、応答がなければFALSEを返す方法はありますか?
Windowsをサポートする必要がないのであれば、実に簡潔な方法があります。
import os
hostname = "google.com" #example
response = os.system("ping -c 1 " + hostname)
#and then check the response...
if response == 0:
print hostname, 'is up!'
else:
print hostname, 'is down!'
これは、pingが接続に失敗した場合に0以外の値を返すからです。(また、 '-t'オプションを使って ping のタイムアウト(秒単位)を変更することもできます。 なお、これはコンソールにテキストを出力します。
1 #!/usr/bin/python
2
3 import os
4 import sys
5 import time
6
7 os.system("clear")
8 home_network = "172.16.23."
9 mine = []
10
11 for i in range(1, 256):
12 z = home_network + str(i)
13 result = os.system("ping -c 1 "+ str(z))
14 os.system("clear")
15 if result == 0:
16 mine.append(z)
17
18 for j in mine:
19 print "host ", j ," is up"
icmplibを使うとroot権限が必要になりますが、以下はうまくいきます。 HTH