如何将脚本用户输入转为cron参数并实现定时ping测试结果对比
Hey there! Let's tackle your two questions with concrete, actionable steps that fit right into your workflow.
1. Replace User Input with Command-Line Arguments (for Cron)
Instead of relying on input() to get pre/post, we can modify your script to accept command-line arguments. This makes it seamless to pass values directly from cron jobs without any manual input.
Here's the adjusted script with argument handling:
#!/usr/bin/env python3 import sys import os # Use absolute paths for result files (critical for cron's minimal environment) BASE_DIR = "/var/log/router_ping_results" PRE_RESULTS_PATH = f"{BASE_DIR}/pre_maintenance.txt" LAST_RESULTS_PATH = f"{BASE_DIR}/last_run.txt" def run_ping_tests(): # Your existing ping test logic here (return dict of router: result) # Example mock data: return { "router_1": "SUCCESS RATE IS 0 PERCENT", "router_2": "SUCCESS RATE IS 100 PERCENT", "router_3": "SUCCESS RATE IS 50 PERCENT" } def save_results(results, file_path): # Create directory if it doesn't exist os.makedirs(os.path.dirname(file_path), exist_ok=True) with open(file_path, "w") as f: for router, result in results.items(): f.write(f"{router}:{result}\n") def load_results(file_path): results = {} with open(file_path, "r") as f: for line in f: router, result = line.strip().split(":", 1) results[router] = result return results def compare_results(previous, current): # Your comparison logic (matches your example rules) print("=== Comparison Results ===") for router in previous: prev_rate = previous[router].split()[-2] curr_rate = current[router].split()[-2] if prev_rate == curr_rate: print(f"{router}: *PASS* (Pre: {prev_rate}% | Post: {curr_rate}%)") else: print(f"{router}: *FAIL* (Pre: {prev_rate}% | Post: {curr_rate}%)") def main(): # Validate command-line arguments if len(sys.argv) != 2: print("Usage: ./ping_script.py [pre|post|auto]") sys.exit(1) mode = sys.argv[1].lower() if mode not in ["pre", "post", "auto"]: print("Error: Argument must be 'pre', 'post', or 'auto'") sys.exit(1) current_results = run_ping_tests() if mode == "pre": save_results(current_results, PRE_RESULTS_PATH) print("Pre-maintenance tests completed. Results saved.") elif mode == "post": if not os.path.exists(PRE_RESULTS_PATH): print("Error: Pre-maintenance results not found. Run 'pre' first.") sys.exit(1) pre_results = load_results(PRE_RESULTS_PATH) compare_results(pre_results, current_results) elif mode == "auto": # Compare against the last run's results, then save current as new last if os.path.exists(LAST_RESULTS_PATH): last_results = load_results(LAST_RESULTS_PATH) compare_results(last_results, current_results) else: print("No previous results found. Saving current run as baseline.") save_results(current_results, LAST_RESULTS_PATH) if __name__ == "__main__": main()
Key improvements:
- Uses
sys.argvto acceptpre/post/autodirectly from the command line - Uses absolute paths for result storage (avoids cron path issues)
- Adds an
automode for comparing against the most recent run - Includes validation for missing arguments or results files
2. Configuring Cron Jobs for Automated Testing
Option A: Pre/Post Maintenance Schedule
If you have fixed maintenance windows, schedule two separate cron jobs:
- Run
prebefore maintenance - Run
postafter maintenance to compare against the pre results
Step 1: Make the script executable
chmod +x /path/to/your/ping_script.py
Step 2: Edit your crontab
Open your user's crontab (use sudo crontab -e if root access is needed for ping tests):
crontab -e
Add these lines (adjust times and paths to match your schedule):
# Run pre-maintenance test at 1:00 AM on the 15th of every month 0 1 15 * * /path/to/your/ping_script.py pre >> /var/log/router_ping_results/cron_pre.log 2>&1 # Run post-maintenance comparison at 3:00 AM on the 15th of every month 0 3 15 * * /path/to/your/ping_script.py post >> /var/log/router_ping_results/cron_post.log 2>&1
- The
>> /var/log/... 2>&1redirects both output and errors to a log file (critical for debugging cron issues) - Ensure the log directory exists and the cron user has write access:
sudo mkdir -p /var/log/router_ping_results sudo chown your_username:your_username /var/log/router_ping_results
Option B: Auto-Compare Every X Interval
If you want to run tests regularly and compare each run against the last one, use the auto mode:
Add this line to your crontab (runs every hour as an example):
# Run test and compare with last run every hour 0 * * * * /path/to/your/ping_script.py auto >> /var/log/router_ping_results/cron_auto.log 2>&1
Critical Cron Best Practices
- Always use absolute paths for scripts, result files, and logs (cron doesn't inherit your user's full
PATH) - Test the script manually first with the command-line argument to confirm it works
- Check system cron logs (usually
/var/log/syslogon Debian/Ubuntu) if jobs fail to run - If ping requires elevated privileges, run the cron job with
sudo crontab -e
内容的提问来源于stack exchange,提问作者Surender Reddy

