有一点问题,我希望创建一个脚本,每 60 秒运行一次以下命令
netstat - tn
这应该给出类似的输出
root@guest:~# netstat -tn
Active Internet connections (w/o servers)
Proto Recv-Q Send-Q Local Address Foreign Address State
tcp 0 111 111.111.141.36:22 111.11.11.223:54327 ESTABLISHED
我只对存储外部地址感兴趣,我该如何实现这一点?
我确实尝试了以下命令
root@guest:~# watch -n 300 netstat -tn > results_mon_27.txt
将所有数据记录到一个文本文件中,但这会导致格式问题,如下所示,所以最好我只收集国外地址
^[[?1049h^[[1;40r^[(B^[[m^[[4l^[[?7h^[[H^[[2JEvery 300.0s: netstat -tn^[[1;138Hguest: Mon Aug 21 16:45:31 2017^[[3;1HActive Internet connections (w/o servers)
^[[4dProto Recv-Q Send-Q Local Address^[[4;45HForeign Address^[[4;69HState
^[[5dtcp^[[5;12H0^[[19G0 45.76.141.36:38708^[[45G192.42.115.102:9004 TIME_WAIT
^[[6dtcp^[[6;12H0 40 45.76.141.36:22^[[6;45H193.36.8.223:54327^[[69GESTABLISHED^[[40;168H^[[1;159H50^[[5;34H22 ^[[5;47H3.36.8.223:54327 ESTABLISHED^[[6;18H6$
^[[5d^[[M^[[1;160H5
^[[6dtcp^[[6;12H0^[[19G0 45.76.141.36:22^[[6;45H58.242.83.32:25719^[[69GESTABLISHED^[[40;168H
^[[6d^[[J^[[1;159H10^[[40;168H
^[[5d^[[L^[[1;160H5
^[[5dtcp^[[5;12H0^[[19G0 45.76.141.36:22^[[5;45H196.200.176.80:37384 ESTABLISHED
^[[7dtcp^[[7;12H0^[[19G0 45.76.141.36:22^[[7;45H58.242.83.32:61038^[[69GESTABLISHED^[[40;168H
^[[5d^[[M^[[1;159H20^[[6;58H49490^[[40;168H^[[1;160H5^[[6;34H38722^[[45G192.42.115.102:9004
^[[7dtcp^[[7;12H0 68 45.76.141.36:22^[[7;45H58.242.83.32:42510^[[69GESTABLISHED^[[40;168H^[[1;159H30^[[7;18H 0^[[7;58H38678^[[40;168H
^[[7d^[[J^[[1;160H5^[[5;45H58.242.83.32:15804^[[6;34H22 ^[[6;47H3.36.8.223:54327 ^[[40;168H
^[[5d^[[M^[[1;159H40
^[[6dtcp^[[6;12H0^[[19G0 45.76.141.36:22^[[6;45H58.242.83.32:14118^[[69GESTABLISHED^[[40;168H^[[1;160H5^[[6;60H003
答案1
由于外部地址是第五列,请尝试使用 的输出,netstat
您awk
可以轻松收集/操作每列数据。
netstat -tn|awk '{print $5}'
输出将仅提供第五列,即国外地址
#!/bin/bash
while true
do
netstat -tn|awk '{print $5}' >> output.netstat
sleep 60
done