Python多远程服务器Ping检测脚本故障排查求助
Fixing Your Python Ping Script Issues
Let's break down what's going wrong with your script and fix it step by step — those weird "Usa..." outputs are from the ping command running without a target IP, which causes it to throw an error message!
Key Issues in the Original Script
- Missing Target IP in Ping Calls: Every time you run
subprocess.call(['ping', '-c', '3']), you're not telling the ping command which IP to ping. This is the main reason for the odd output. - Misused Global Variables: You opened the file outside the function and relied on a global
responsevariable that has no connection to the current IP being tested. - Unsafe File Handling: You didn't close the file after reading it, which can lead to unnecessary resource leaks.
- Unstripped Line Breaks: Lines read from the file include newline characters, which will mess up your output formatting.
- Python 2 Syntax:
print linesis Python 2-specific syntax — if you're using Python 3, this will throw a syntax error immediately.
Corrected Script
import subprocess def check_IP_from_file(filename): # Use 'with' statement to auto-close the file after reading (no manual cleanup needed) with open(filename, "r") as file: for line in file: # Remove newline characters and extra whitespace from the IP string ip_address = line.strip() # Skip empty lines in the file to avoid unnecessary checks if not ip_address: continue # Run ping command with the target IP # '-c 3' sends 3 packets; '-W 2' sets a 2-second timeout to speed up checks ping_result = subprocess.call( ['ping', '-c', '3', '-W', '2', ip_address], # Suppress ping's default output so it doesn't clutter your script's results stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL ) # Check ping exit code: 0 = success (reachable), non-zero = failure (unreachable) if ping_result == 0: print(f"{ip_address} is reachable") else: print(f"{ip_address} is unreachable") # Call the function with your IP list file check_IP_from_file('IPlist.txt')
What Changed & Why
- Added Target IP to Ping Command: We now pass
ip_addressas the final argument to the ping command, so it knows exactly which server to test. - Used
withfor File Handling: This ensures the file is automatically closed when we're done reading it, no matter what happens during execution. - Stripped Line Content:
line.strip()removes newline characters and extra spaces from each IP entry, making your output clean and consistent. - Skipped Empty Lines: The script now ignores any blank lines in your
IPlist.txtfile, so you don't get irrelevant status messages. - Suppressed Ping Output: We added
stdout=subprocess.DEVNULLandstderr=subprocess.DEVNULLto hide the raw ping command output, so your script only shows the reachability status you care about. - Python 3 Compatible: Used f-strings (
f"{ip_address}...") and parentheses inprint(), which works seamlessly in Python 3 (and most recent Python 2 versions too).
Quick Usage Note
Make sure your IPlist.txt has one IP address per line, like this:
8.8.8.8 1.1.1.1 192.168.1.1
Run the script, and you'll get clear, readable output like:
8.8.8.8 is reachable 1.1.1.1 is reachable 192.168.1.1 is unreachable
内容的提问来源于stack exchange,提问作者Alec M
相关产品推荐
相关产品推荐

