Nathaniel Davidson
Nathaniel Davidson

Reputation: 137

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. I'm not asking for an easy answer, just a clue as to where I would start. THANKS!

Upvotes: 1

Views: 1449

Answers (2)

salparadise
salparadise

Reputation: 5805

Not quite bash but perl, but it does what you want, here is the whole script:

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

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

returns all remote addresses found in "/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. (Since $old is not populated on the first try, it will write all the addresses on the first loop) and sleeps for two seconds.

 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;

}

Upvotes: 1

michael_stackof
michael_stackof

Reputation: 223

1.exec netstat & get the ip address
2.grep ip result.txt
3.if there is no that ip, write this one,otherwise don't.

You can crontab to exec your script.

Upvotes: 0

Related Questions