i have been looking for a utility on mac os x which would allow me to track or log my network traffic. after a fruitless search for a program who would do this for me, i got a hint for a command line tool:
netstat
after having a look at the man page of netstat i knew that this is
the utility i was looking for. now how to organize it so i can record and manage the activities in a useful way?
i need:
- some independency from the terminal, i.e. write logs to a file
- netstat should run all the time
- logfile should not become too big
solutions i found:
$ sudo netstat -i -w 60 >> /Library/Logs/netstat.log &
calling netstat with parameter
i makes it select the default network interface;
parameter
w 60 makes it wait 60 seconds before it prints again.
sudo executes the command as root user.
>> appends the output to netstat.log, where i can access it easily with console.app.
& at the end frees the terminal, so i can use it again for other things.
watch out: if the terminal window is closed, also netstat is gone!
then, to keep this file at a reasonable size, i edited the crontab:
$ sudo emacs /private/etc/crontab
this is the file which keeps information about processes which have to be carried out regularly, so called cron jobs
(1). it can only be changed changed with root rights, therefore use
sudo.
it contains the following lines now:
1 * * * * root echo ============== >> /Library/Logs/netstat.log
1 * * * * root nice -n 20 date >> /Library/Logs/netstat.log
1 * * * * root echo ============== >> /Library/Logs/netstat.log
to make it easier to navigate in the log file, i print the hour and date every hour.
# each day at 00:03 backup the current netstat.log
3 0 * * * root nice -n 20 cat /Library/Logs/netstat.log >> /Library/Logs/netstat_bak.log
# after having made a backup, erase the current netstat.log
4 0 * * * root nice -n 20 rm -rf /Library/Logs/netstat.log
# erase at week interval the backup file
2 0 * * 1 root nice -n 20 rm -rf /Library/Logs/netstat_bak.log
adding the nice command before the actual command will cause the command to be executed with lowest priority (range is from -20, the highest, to 20, the lowest). for more information see
$ man nice.
so this gives a handy solution which doesn't require any human intervention, except at startup i have to run the netstat command manually.
(1) a tutorial for crontab can be found on www.macdevcenter.com, which is actually entitled "learning the mac os x terminal" but in which the functionality of crontab is described pretty well.
update: see also the information given the following day.