我想每 1 秒将命令的输出重定向tcptrack -i wlp3s0
到日志文件。
为此,我找到了这个脚本:
#!/usr/bin/env bash
file="file_$((SECONDS / 10))0.txt" # calculate our initial filename
exec 3>"$file" # and open that first file
exec 4< <(echo <password>|sudo -S tcptrack -i wlp3s0) # also open a stream coming from nc on FD #4
while IFS= read -r line <&4; do # as long as there's content to read from nc...
sleep 1
printf '%s\n' "$line" >&3 # write our line to whichever file is open on FD3
done
除了我得到奇怪的输出外,脚本运行正常:
[?1049h[22;0;0t[1;53r(B[m[4l[?7h[?1h=[H[2Jl(B[0;7m Client [15bServer [15bState [7bIdle A Speed [8b
[52d TOTAL [58b0 B/s [8b
Connections 0-0 of 0 [24bUn(B[0;4;7mp(B[0;7maused Un(B[0;4;7ms(B[0;7morted [14b[53;65H(B[me(B[0;7m (B[mn(B[0;7m (B[mo(B[0;7m (B[mv(B[0;7m (B[mo(B[0;7m (B[m[H
1**.***.*1*.*4*:**** ***.***.***.***:**** ESTABLISHED 0s * 0 B/s[53;14H(B[0;7m1-1 of 1[53;65H(B[m[2;64H [53;65H[2;64H*[53;65H[2;64H [53;65H[2;64H*[53;65H[2;64H [53;65H[2;64H*[53;65H[2;64H [53;65H[2;51r[2;1HM[1;53r[2;2H***.***.**.**:***** ***.***.***.***:****[46GSYN_SENT 0s 0 B/s[53;16H(B[0;7m2 of 2[53;65H(B[m[2;46HESTABLISHED[64G*[53;65H[2;64H [53;65H[3;64H*[53;65H[3;64H [53;65H[3;64H*[53;65H[3;64H [53;65H[3;64H*[53;65H[3;64H [53;65H[3;64H*[53;65H[3;64H [53;65H
[4d ***.***.***.***:***** ***.***.***.***:******[46GSYN_SENT 0s 0 B/s[53;16H(B[0;7m3 of 3[53;65H(B[m[3;64H*[53;65H[3;64H [53;65H[3;64H*[53;65H[3;64H [53;65H[2;64H*[53;65H[2;64H [53;65H[2;64H*[53;65H[2;64H [53;65H[2;64H*[53;65H[2;64H [53;65H[2;64H*[53;65H[2;64H [53;65H[3;64H*[4;49H|ACK-ACK[64G*[53;65H[3;64H
[53;65H[4;46HESTABLISHED[64G*[53;65H[4;64H [53;65H[2;64H*[53;65H[2;64H [53;65H[2;64H*[53;65H[2;64H [53;65H[2;64H*
PS:我用 * 替换了 IP 地址。
如何修复输出,使其与终端上的命令输出相同?
答案1
tcptrack
是一个基于 ncurses 的工具,我认为尝试捕获其输出是没有意义的 - 您看到的是转义序列。我认为如果您netstat -t
每秒都这样做,您将获得与您想要实现的结果非常相似的日志。
(顺便说一句,您可能希望将自己添加为“NOPASSWD”sudoer netstat
。)