如何为Linux上的Python MTR脚本添加-o输出参数以获取自定义粒度信息?
Got it, let's walk through how to add your desired mtr output parameters to the Python script. The key is finding where the script calls the mtr command and inserting your -o flag there.
Step 1: Locate the mtr command invocation in the script
Open up the smokeping-mtr-alert.py file and search for sections where the script runs the mtr executable. You'll typically find this using Python's subprocess module (like subprocess.run(), subprocess.Popen(), or subprocess.check_output()).
A common snippet might look like this (the exact code may vary slightly depending on the script version):
# Example original code calling mtr mtr_command = [ 'mtr', '--report', '--report-cycles', str(ping_count), target_host ] result = subprocess.run(mtr_command, capture_output=True, text=True)
Step 2: Insert the -o parameter into the command list
Since subprocess expects command arguments as a list, you'll add two new elements to the command list: -o and your output string LSRD NBWA JXIM V.
Here's how the modified code will look:
# Modified code with custom output modifier mtr_command = [ 'mtr', '--report', '--report-cycles', str(ping_count), '-o', 'LSRD NBWA JXIM V', # New line added here target_host ] result = subprocess.run(mtr_command, capture_output=True, text=True)
Step 3: Verify the changes
Run the script as you normally would. The mtr output captured by the script should now include the granular metrics specified by your -o flag:
- L: Loss ratio
- S: Sent packets
- R: Received packets
- D: Dropped packets
- N: Newest latency
- B: Best latency
- W: Worst latency
- A: Average latency
- J: Jitter
- X: Interarrival jitter
- I: Packet size
- M: MTU size
- V: IPv6 hop limit / IPv4 TTL
If the script parses the mtr output later on, you may need to adjust the parsing logic to handle the new column order/fields. But if you're just capturing the raw output for alerts, this change should work directly.
内容的提问来源于stack exchange,提问作者Kammo

