在Python中,你可以使用subprocess模塊來調用ping命令
import subprocess
def ping(host, timeout=2):
try:
# 在Windows系統中,使用'-n'參數,而在Linux和macOS系統中,使用'-c'參數
command = ['ping', '-c', '1', host, '-W', str(timeout)] if platform.system().lower() != 'windows' else ['ping', '-n', '1', host, '-w', str(timeout)]
subprocess.check_output(command, stderr=subprocess.STDOUT)
return True
except subprocess.CalledProcessError as e:
print(f"請求超時或目標不可達: {e.output.decode('utf-8')}")
return False
except FileNotFoundError:
print("ping命令未找到,請確保你的系統已安裝ping工具。")
return False
if __name__ == "__main__":
host = input("請輸入要ping的主機地址: ")
if ping(host):
print(f"{host} 在線")
else:
print(f"{host} 離線")
這個示例定義了一個名為ping的函數,它接受一個主機地址和一個可選的超時參數(默認為2秒)。函數使用subprocess.check_output()執行ping命令,并檢查返回值。如果ping成功,函數返回True,否則返回False。
請注意,這個示例僅適用于Python 3。如果你使用的是Python 2,你需要對代碼進行一些修改,例如使用raw_input()代替input()。