简体   繁体   English

Bash脚本将netstat输出附加到文件?

[英]Bash script to append netstat output to file?

being a big fan of learning the basics before tackling more advanced projects, I ask this question with a sigh and a shake of my head...I like to monitor incoming/outgoing connections in realtime ( netstat -natuec ) but sometimes I get caught up in what I'm doing...So I would like to create a script that would append any NEW ip address that shows up from the netstat command to a txt file for review later. 作为在处理更高级的项目之前学习基础知识的忠实粉丝,我叹了口气并摇了摇头,问这个问题...我喜欢实时监视传入/传出的连接(netstat -natuec),但有时我会陷入困境因此,我想创建一个脚本,该脚本会将从netstat命令显示的任何 IP地址附加到txt文件中,以供以后查看。 I'm not asking for an easy answer, just a clue as to where I would start. 我并不是要一个简单的答案,而只是想知道从哪里开始。 THANKS! 谢谢!

Not quite bash but perl, but it does what you want, here is the whole script: 虽然不是bash而是perl,但是它可以实现您想要的功能,这是整个脚本:

use warnings;
use strict;
use Socket;
use feature 'say';

sub hex_to_ip {my $i = shift; inet_ntoa( pack( "N", hex( $i ) ) )}
sub addresses {open(my $net,"<","/proc/net/tcp"); my %add;while(<$net>) {my $r = (split " ",$_)[2];$r =~ s/(rem.*|:.*)//; $add{hex_to_ip($r)}++}; return %add};

my %old;
while(1) {
open(my $new_file,">>","/tmp/new_connections.txt");
my %fresh = &addresses;
for my $f(keys %fresh) {
    my $current_time = localtime;
    say $new_file "$f $current_time\n" unless exists $old{$f};
}
close $new_file;
say "!!"; %old = %fresh; sleep 2;
}

function to convert hex to ip 将十六进制转换为ip的函数

sub hex_to_ip {my $i = shift; inet_ntoa( pack( "N", hex( $i ) ) )} 

returns all remote addresses found in "/proc/net/tcp" 返回在“ / proc / net / tcp”中找到的所有远程地址

sub addresses {open(my $net,"<","/proc/net/tcp"); 
   my %add;while(<$net>) {my $r = (split " ",$_)[2];
   $r =~ s/(rem.*|:.*)//; $add{hex_to_ip($r)}++}; return %add
 } 

opens a file for appending (does not clobber what is in it) 打开一个文件进行追加(不会破坏其中的内容)

open(my $new_file,">>","/tmp/new_connections.txt"); 

runs the entire life of the program 运行程序的整个生命

while(1)

Gets a fresh copy of the current addresses, and if $old does not have them, it writes to the file with a timestamp. 获取当前地址的新副本,如果$ old没有这些副本,它将使用时间戳写入文件。 (Since $old is not populated on the first try, it will write all the addresses on the first loop) and sleeps for two seconds. (由于第一次尝试时未填充$ old,它将在第一个循环中写入所有地址)并休眠两秒钟。

 my %fresh = &addresses;
for my $f(keys %fresh) {
    my $current_time = localtime;
    say $new_file "$f $current_time" unless exists $old{$f};
}
say "!!"; %old = %fresh; sleep 2;

} }

1.exec netstat & get the ip address 1.执行netstat并获取IP地址
2.grep ip result.txt 2. grep ip result.txt
3.if there is no that ip, write this one,otherwise don't. 3.如果没有那个ip,写这个,否则不要写。

You can crontab to exec your script. 您可以crontab执行脚本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM