network_connection_checker.py
· 1.4 KiB · Python
Brut
import subprocess
import platform
import time
def ping_once(host):
"""
使用系統的 ping 指令對指定 host 發送一次封包,
回傳 True 代表 ping 成功,False 代表失敗。
"""
# 根據作業系統決定參數:Windows 用 -n,其他平台用 -c
param = '-n' if platform.system().lower() == 'windows' else '-c'
command = ['ping', param, '1', host]
try:
# 不顯示輸出
result = subprocess.run(command, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
return result.returncode == 0
except Exception as e:
print(f"呼叫 ping 指令發生例外:{e}")
return False
def is_network_connected(host='8.8.8.8', attempts=5, success_threshold=3, delay=1):
"""
透過連續 ping 嘗試判斷網路連線狀態:
- attempts: ping 嘗試次數
- success_threshold: 成功次數達此值才視為連線正常
- delay: 每次 ping 之間的等待秒數
"""
success_count = 0
for i in range(attempts):
if ping_once(host):
success_count += 1
print(f"[{i+1}/{attempts}] Ping 成功")
else:
print(f"[{i+1}/{attempts}] Ping 失敗")
# 避免連續發送太快
time.sleep(delay)
return success_count >= success_threshold
if __name__ == '__main__':
if is_network_connected():
print("網路連線正常")
else:
print("網路連線有問題")
| 1 | import subprocess |
| 2 | import platform |
| 3 | import time |
| 4 | |
| 5 | def ping_once(host): |
| 6 | """ |
| 7 | 使用系統的 ping 指令對指定 host 發送一次封包, |
| 8 | 回傳 True 代表 ping 成功,False 代表失敗。 |
| 9 | """ |
| 10 | # 根據作業系統決定參數:Windows 用 -n,其他平台用 -c |
| 11 | param = '-n' if platform.system().lower() == 'windows' else '-c' |
| 12 | command = ['ping', param, '1', host] |
| 13 | try: |
| 14 | # 不顯示輸出 |
| 15 | result = subprocess.run(command, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) |
| 16 | return result.returncode == 0 |
| 17 | except Exception as e: |
| 18 | print(f"呼叫 ping 指令發生例外:{e}") |
| 19 | return False |
| 20 | |
| 21 | def is_network_connected(host='8.8.8.8', attempts=5, success_threshold=3, delay=1): |
| 22 | """ |
| 23 | 透過連續 ping 嘗試判斷網路連線狀態: |
| 24 | - attempts: ping 嘗試次數 |
| 25 | - success_threshold: 成功次數達此值才視為連線正常 |
| 26 | - delay: 每次 ping 之間的等待秒數 |
| 27 | """ |
| 28 | success_count = 0 |
| 29 | for i in range(attempts): |
| 30 | if ping_once(host): |
| 31 | success_count += 1 |
| 32 | print(f"[{i+1}/{attempts}] Ping 成功") |
| 33 | else: |
| 34 | print(f"[{i+1}/{attempts}] Ping 失敗") |
| 35 | # 避免連續發送太快 |
| 36 | time.sleep(delay) |
| 37 | return success_count >= success_threshold |
| 38 | |
| 39 | if __name__ == '__main__': |
| 40 | if is_network_connected(): |
| 41 | print("網路連線正常") |
| 42 | else: |
| 43 | print("網路連線有問題") |
| 44 |