如何将tcptrack的输出保存到文本文件?已尝试grep和cut但无效
Got it, I totally get why grep/cut aren't working here—tcptrack uses curses to render that dynamic, updating terminal interface, which means regular redirection or pipe tools can't properly capture the changing screen content. Let's walk through a few reliable solutions to save its output to a text file:
script Command (Easiest Approach) The script tool is built specifically to record terminal sessions, including output from curses-based programs like tcptrack. It captures every bit of what's displayed in the terminal, even the dynamic updates.
- Start a script session that runs tcptrack directly, specifying your output file:
Replacescript -c "tcptrack -i eth0" tcptrack_output.txteth0with your network interface name, andtcptrack_output.txtwith whatever filename you want to save to. - When you're done capturing, press
Ctrl+Cto stop tcptrack—scriptwill automatically end the session and save all output to your file. - To view the output properly (since it might include curses control characters), use
less -Rorcat -v:
Theless -R tcptrack_output.txt-Rflag tellslessto interpret color and formatting escape codes correctly.
tcpdump + Analyze Later (For Data-Only Needs) If you don't need the exact dynamic interface of tcptrack, just the connection and traffic statistics it shows, using tcpdump to capture packets and then analyzing them with a tool like tshark is a more flexible approach.
- Capture packets to a file first:
tcpdump -i eth0 -w tcptrack_capture.pcap - Stop the capture with
Ctrl+C, then analyze the pcap file to get connection stats similar to tcptrack:
This outputs a clean, static list of TCP connections with byte counts—you can redirect this directly to a file withtshark -r tcptrack_capture.pcap -q -z conv,tcp> tcp_connections.txt.
strace to Capture Output (More Technical) If you want to directly capture the output tcptrack sends to the terminal, you can use strace to trace its write system calls. This skips the curses terminal control layer and grabs the raw output.
- Run tcptrack with
straceto log write operations to stdout/stderr:strace -e write=1,2 -o tcptrack_strace.txt tcptrack -i eth0 - Clean up the output file to remove
strace's metadata and extract the actual tcptrack content:
This will give you a plain-text version of the output, though you might need to do some extra trimming to remove leftover control characters.grep -o '"[^"]*"' tcptrack_strace.txt | tr -d '"' > tcptrack_cleaned.txt
Quick Recommendation
Stick with the script method if you want to preserve the full dynamic interface of tcptrack. If you only care about the underlying connection data, tcpdump + tshark is cleaner and easier to work with for post-processing.
内容的提问来源于stack exchange,提问作者Rohit_Srivastav

