Skip to content

Commit

Permalink
Adds version number option and command line arguments. Minor README u…
Browse files Browse the repository at this point in the history
…pdates.
  • Loading branch information
stalexan committed Sep 22, 2012
1 parent 8a88f98 commit 2cf3879
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 20 deletions.
1 change: 1 addition & 0 deletions README
14 changes: 8 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@ Netstat-monitor -- Monitor network connections on your system

## Description

Netstat-monitor is a command line tool for monitoring network connections. Its output looks similar to the output from the netstat command with the options "netstat --inet -alp". One difference is that netstat-monitor can be left running, and will report new connections as they are made. Also, filters can be created to limit what's displayed to just what's unexpected or interesting.
Netstat-monitor is a command line tool for monitoring network connections. Its output looks similar to the output from the netstat command with the options "netstat --inet -alp". Netstat-monitor can be left running, though, and will report new connections as they are made. Also, filters can be created to limit what's displayed to just what's unexpected or interesting.

## Installation

Netstat-monitor was written and tested on an Ubuntu 12.04 machine with Python 3.2. It should work fine on most recent distributions of Linux, though.
Netstat-monitor was written and tested on an Ubuntu 12.04 machine with Python 3.2. It should work fine on other recent distributions of Linux too, as long as the files tcp and udp in /proc/net have the expected format. Netstat-monitor will do a basic check on the header of these files on startup, to see if they are what it expects.

To get the latest version:

Expand All @@ -27,7 +27,9 @@ Install, on a Debian or Ubuntu machine:
$ sudo apt-get install python3
$ sudo python setup.py install

Or, the install step can be skipped and netstat-monitor can be run from the directory the files were extracted to.
This will install the netstat-monitor exe to /usr/local/bin/ and the netstat.py module to /usr/local/lib/python3.2/dist-packages/.

Optionally, the install step can be skipped and netstat-monitor can be run directly from where the files were extracted.

## Running

Expand All @@ -53,7 +55,7 @@ Filters are created in config files that are listed on the command line. For exa

netstat-monitor sample-filters

The file sample-filters is provided with the install, and has some example filters:
The file [sample-filters](https://github.com/stalexan/netstat-monitor/blob/master/sample-filters) is provided with the install, and has some example filters. A few of them are:

[ntpupdate]
exe: /usr/sbin/ntpdate
Expand All @@ -69,7 +71,7 @@ The file sample-filters is provided with the install, and has some example filte
user: root
states = FIN_WAIT1, FIN_WAIT2, TIME_WAIT, CLOSE, CLOSE_WAIT, LAST_ACK, CLOSING

Each section defines a new filter. A section starts with the filter name, enclosed in square brackets. Each line after that defines a filter parameter. For example, the first section defines a filter called ntpupdate that has two parameters: exe and user. This filter will look for connections with exe set to /usr/sbin/ntpupdate and user set to root. Any connections with these settings will be filtered out, and not displayed.
Each section defines a new filter. A section starts with the filter name, enclosed in square brackets. The name can be any alphanumeric string. Each line after that defines a filter parameter. For example, the first section defines a filter called ntpupdate that has two parameters: exe and user. This filter will look for connections with exe set to /usr/sbin/ntpupdate and user set to root. Any connections with these settings will be filtered out, and not displayed.

The available filter parameters are:

Expand All @@ -81,5 +83,5 @@ The available filter parameters are:
* local_ports: Comma separated list of local ports.
* remote_hosts: Comma separated list of remote hosts.
* remote_ports: Comma separated list of remote ports.
* states: Connection states.
* states: Comma separated list of Connection states.

36 changes: 23 additions & 13 deletions netstat.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@
Variables:
MONITOR_INTERVAL -- How often Monitor collects netstat snapshots, in seconds.
DEFAULT_MONITOR_INTERVAL -- How often Monitor collects netstat snapshots, in seconds.
MIN_MONITOR_INTERVAL -- Minimum value for monitor interval.
CLEAN_INTERVAL -- How often the list of connections is reset, in minutes.
LOOKUP_REMOTE_HOST_NAME -- Whether to convert IP addresses to host names.
Expand All @@ -48,10 +49,13 @@
import sys
import time

MONITOR_INTERVAL = 1 # Number of seconds between each netstat.
CLEAN_INTERVAL = 5 # Number of minutes "seen" list grows before being cleaned out.
__version__ = "1.0"

LOOKUP_REMOTE_HOST_NAME = True # Whether to convert IP addresses to host names by doing a hosth name lookup.
DEFAULT_MONITOR_INTERVAL = 1 # Number of seconds between each netstat.
MIN_MONITOR_INTERVAL = 0.001 # Minimum value for monitor interval.
CLEAN_INTERVAL = 5 # Number of minutes "seen" list grows before being cleaned out.

LOOKUP_REMOTE_HOST_NAME = True # Whether to convert IP addresses to host names by doing a host name lookup.

PROC_TCP = "/proc/net/tcp"
PROC_UDP = "/proc/net/udp"
Expand Down Expand Up @@ -552,17 +556,20 @@ class Monitor():
"""Monitor creates, filters, and reports SocketInfos at regular intervals."""
_closing_states = ['FIN_WAIT1', 'FIN_WAIT2', 'TIME_WAIT', 'CLOSE', 'CLOSE_WAIT', 'LAST_ACK', 'CLOSING']

def __init__(self, interval = MONITOR_INTERVAL, filter_files = None):
def __init__(self, interval = DEFAULT_MONITOR_INTERVAL, filter_files = None):
"""Create a Monitor that monitors every interval seconds using the specified filters."
Keyword arguments:
interval -- Number of seconds between each time Monitor creates a Netstat. Defaults
to MONITOR_INTERVAL.
to DEFAULT_MONITOR_INTERVAL.
filters -- List of filters to limit what SocketInfos are displayed to the user. Any
SocketInfos that match a filter are not displayed. Optional.
"""
if interval < MIN_MONITOR_INTERVAL:
raise MonitorException("ERROR: Monitor interval needs to be at least {0}".format(MIN_MONITOR_INTERVAL))

self._interval = interval
self._seen = {}

Expand Down Expand Up @@ -675,9 +682,9 @@ def _filter_socket(self, socket_info):
# of states to end.
# -- Process exited. The socket could still be exist, if the process that exited
# did an exec and the child process now owns the socket. It should be seen the
# next time a NetStat is done.
# One variable in all of this is MONITOR_INTERVAL, which determines how often the
# /proc/net files are read. The files are read every MONITOR_INTERVAL seconds. The lower
# next time a NetStat is done, as owned by the child.
# One variable in all of this is monitor_interval, which determines how often the
# /proc/net files are read. They're read every monitor_interval seconds. The lower
# this value, the less likely it is a socket will not be seen. However, CPU load goes up.
pid = socket_info.lookup_pid()
if pid is None:
Expand Down Expand Up @@ -731,7 +738,7 @@ def _clean(self):
#sys.stdout.flush()

def monitor(self):
"""Perform a NetStat every MONITOR_INTERVAL seconds."""
"""Perform a NetStat every monitor_interval seconds."""
# Print header
print("Time Proto ID User Local Address Foreign Address State PID Exe Command Line")
sys.stdout.flush()
Expand All @@ -743,14 +750,17 @@ def monitor(self):

def main():
# Parse comomand line
parser = argparse.ArgumentParser()
parser.add_argument('filter_files', nargs='*', help='config files that define filters')
parser = argparse.ArgumentParser(prog='netstat-monitor', description='Monitor network connections.')
parser.add_argument('--version', action='version', version='%(prog)s ' + __version__)
parser.add_argument('-m', '--monitor-interval', type=float, default=float(DEFAULT_MONITOR_INTERVAL),
help='How often to check for new connections, in seconds.')
parser.add_argument('filter_file', nargs='*', help='Config file that defines filters')
args = parser.parse_args()

# Monitor
return_code = 0
try:
monitor = Monitor(1, args.filter_files)
monitor = Monitor(args.monitor_interval, args.filter_file)
monitor.monitor()
except KeyboardInterrupt:
print('')
Expand Down
3 changes: 2 additions & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,11 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.

from distutils.core import setup
from netstat import __version__

setup(
name='netstat-monitor',
version='1.0c1',
version=__version__,
py_modules=['netstat'],
scripts=['netstat-monitor'],
data_files=[('', ['sample-filters'])],
Expand Down

0 comments on commit 2cf3879

Please sign in to comment.