Refreshing Netstat Output with Perl VIEW Rotwild, Photocase.Com

Refreshing Netstat Output with Perl VIEW Rotwild, Photocase.Com

Perl: Dynamic netstat PROGRAMMING NETWORKRefreshing netstat output with Perl VIEW rotwild, photocase.com rotwild, The netstat utility reveals how your Linux box interacts with the local network. With a few Perl modules, you can develop a tool that displays the data dynamically, exactly the way top does. BY MICHAEL SCHILLI hen you want to know which Environment (POE), making it possible well as stdout events from other POE ports are currently being used, to execute many different tasks within a sessions. Wyou call netstat. This practical process or a thread. The netstat command should also play Linux utility can be run in several well with the POE kernel, which should modes, which the user controls through Don’t Freeze! start the process but not wait for the command-line options. For example, the As with all GUI applications that call result. Rather, it immediately should re- -s option produces network traffic statis- other programs, you will encounter a turn control to the kernel so that the tics (Figure 1), and -put displays the problem. While the external program latter can again refresh the output and ports of all applications that are cur- runs, the calling application no longer rently communicating over TCP (Figure reacts to user input and mouse clicks, 2). Both outputs are useful, but what is giving the user the impression that the really interesting is the chronological application is frozen. progression of events rather than a snap- The netstat command generally fin- shot at a given moment. ishes quite quickly, but with the -put op- tion, it resolves the hostname of the IP Top for the Network address associated with a socket with a The top utility serves as a model for this reverse DNS lookup. With a slow DNS kind of dynamic output, displaying and server or many sockets, this can lead to continually updating the CPU load, considerable delays; sometimes it takes memory usage, and other basic data of several seconds for netstat to complete. currently running processes. Thanks to Delays can be prevented with the -n op- CPAN, creating a dynamic terminal ap- tion, but the user must be content with plication like this from the static output just the IP address. But users want it all: from top is not really difficult. the luxury of name resolution and a fast- The Curses::UI module delivers the reacting GUI at the same time. necessary framework here, providing the dynamic output and making it possible Racer Components to react to keys pressed by the user. The The GUI application based on Curses::UI Figure 1: The netstat -s command delivers module’s event loop can be merged works together with the POE kernel, pro- statistical data about network traffic easily into the kernel of the Perl Object cessing key presses and mouse clicks as managed by Linux. APRIL 2008 ISSUE 89 73 073-078_perl.indd 73 13.02.2008 16:51:51 Uhr PROGRAMMING Perl: Dynamic netstat react to GUI events. If the output from netstat fi- nally arrives, the kernel again receives this as an event and calls a function that filters and stores the data into varaibles for subsequent processing. The POE::Wheel::Run module is a component of Figure 2: The output of the netstat -put command shows a list of all active TCP ports. the POE distribution from CPAN. The module takes care of an ex- automaton gets a time slice but must thing (hard disk, a network event, or ternal process and changes the state of guarantee that all of the registered ses- output from an external process) play an automaton in case something hap- sions eventually get a turn. In contrast along. An inconsiderate component can pens on the standard output of the pro- to a preemptive Linux kernel that some- paralyze the entire system. Each session cess. Other events occur if the process times pulls the rug out from under a pro- has a private data area – the heap – ends successfully or if an error occurs. cess, the POE framework relies on the which is implemented as hash and amicable behavior of all sessions. stores key-value pairs with session data. Wheels in the Kernel Each session must immediately return The wheel, in turn, finds its place in a control to the kernel, as soon as it can Autonomous Automatons POE::Session, a state automaton, which no longer run at full speed. With this co- The POE world encapsulates autono- latches itself into the POE kernel. The operative multitasking, it is important mous state automatons in so-called com- kernel ensures that now and then the that all tasks that are waiting for some- ponents. The application simply loads Listing 1: PoCoRunner.pm 01 package PoCoRunner; 31 61 $heap->{"wheel"} = $wheel; 02 use strict; 32 ############################# 62 $heap->{"stdout"} = ""; 03 use warnings; 33 sub _start { 63 } 04 use POE::Wheel::Run; 34 ############################# 64 05 use POE; 35 my ( $kernel, $session ) = 65 ############################# 06 36 @_[ KERNEL, SESSION ]; 66 sub stdout { 07 ############################# 37 $kernel->post( $session, 67 ############################# 08 our $PKG = __PACKAGE__; 38 "run" ); 68 my ( $input, $heap ) = 09 39 } 69 @_[ ARG0, HEAP ]; 10 ############################# 40 70 11 sub new { 41 ############################# 71 $heap->{stdout} .= 12 ############################# 42 sub run { 72 "$input\n"; 13 my ( $class, %options ) = 43 ############################# 73 } 14 @_; 44 my ( $kernel, $heap, 74 15 45 $session ) 75 ############################# 16 my $self = {%options}; 46 = @_[ KERNEL, HEAP, 76 sub finish { 17 47 SESSION ]; 77 ############################# 18 POE::Session->create( 48 78 my ( $kernel, $heap ) = 19 package_states => [ 49 my $wheel = 79 @_[ KERNEL, HEAP ]; 20 $PKG => [ 50 POE::Wheel::Run->new( 80 21 qw(_start stdout 51 Program => $heap->{self} 81 ${ $heap->{self}->{data} } 22 finish run) 52 ->{command}, 82 = $heap->{stdout}; 23 ] 53 ProgramArgs => [ 83 24 ], 54 $heap->{self}->{args} 84 $kernel->delay( "run", 25 heap => 55 ], 85 $heap->{self} 26 { self => $self }, 56 StdoutEvent => "stdout", 86 ->{interval} ); 27 ); 57 ErrorEvent => "finish", 87 } 28 58 CloseEvent => "finish", 88 29 bless $self, $class; 59 ); 89 1; 30 } 60 74 ISSUE 89 APRIL 2008 073-078_perl.indd 74 13.02.2008 16:52:05 Uhr Perl: Dynamic netstat PROGRAMMING these classes and creates new objects the constructor new->() has received a • _run: Fires off the process as needed, and the POE kernel includes reference to it from the calling program, • _stdout: Process sends a batch of data their state machines and runs them the main script nettop ends up with the to stdout autonomously behind the scenes. output data in either $stats_data or • _finish: Process terminates The PoCoRunner.pm listing (PoCo is $conns_data. POE maps these states to the functions the usual abbreviation for POE Compo- Subsequently, finish(), starting from of the same name within the module nent) shows a component that takes the line 76, calls the kernel method delay() PoCoRunner.pm, based on the parameter name of a program (netstat, for exam- and causes it to call the PocoRunner package_states in line 19. ple) with options and creates a “wheel,” method run() with a pre-defined delay, which then shoots off an external pro- which then resets the heap-variable data Parameters POE-Style cess with the given program (Listing 1). and again calls the wheel POE::Wheel:: POE passes session parameters in its Afterward, the wheel immediately re- Run with the specified external program own way; for example, if you have an turns control again to the kernel without netstat. event handler taking arguments like waiting for the result. Thus, if someone links this component With each line that appears on the into a POE program and calls the con- my($kernel, $heap) = standard output of the process, POE re- structor with an external command plus @_[KERNEL, HEAP]; ceives a stdout event and calls the PoCo- command-line parameters, an interval Runner.pm method stdout(). There, the duration, and a reference to a scalar, the the session passes the handler a set of session-specific heap variable data (a component not only starts the external arguments in the Perl-typical array @_. scalar) collects the process output as command again and again, but also The handler grabs only two of these text. If netstat has terminated, the au- ensures that the newest and complete through the macros KERNEL and HEAP. tomaton changes to the method finish(), output is stored in the scalar. These constant functions are imported regardless of whether the process has The PoCoRunner state automaton is by POE into the namespace and return terminated successfully or there was an defined by calling the POE::Session’s integer values, so the construct above error. It then copies the collected stdout create() method in line 18. represents a so-called array slice, which data into the scalar instance variable The states are: returns a subset of the parameters in the data of the PoCoRunner object. Because • _start: Start state array as a list. the mathematics of humour TWELVE Quirky Humans, Over Two Million Geeks around the world can’t be wrong! TWO Lovecraftian Horrors, COME JOIN THE INSANITY! ONE Acerbic A.I., ONE Fluffy Ball of Innocence and TEN Years of Archives EQUALS ONE Daily Cartoon that Covers the Geek Gestalt from zero to infinity! APRIL 2008 ISSUE 89 75 073-078_perl.indd 75 13.02.2008 16:52:05 Uhr PROGRAMMING Perl: Dynamic netstat The nettop listing (Listing 2) pulls in The function conns_parse in line 241 On the other hand, stats_parse in line two instances of PoCoRunner in lines 12 works through the netstat output (Figure 173 analyzes the output from netstat -s, and 18: one for netstat -s and an addi- 2), extracts the important columns (local as in Figure 1, and stores the output in a tional one for netstat -put.

View Full Text

Details

  • File Type
    pdf
  • Upload Time
    -
  • Content Languages
    English
  • Upload User
    Anonymous/Not logged-in
  • File Pages
    6 Page
  • File Size
    -

Download

Channel Download Status
Express Download Enable

Copyright

We respect the copyrights and intellectual property rights of all users. All uploaded documents are either original works of the uploader or authorized works of the rightful owners.

  • Not to be reproduced or distributed without explicit permission.
  • Not used for commercial purposes outside of approved use cases.
  • Not used to infringe on the rights of the original creators.
  • If you believe any content infringes your copyright, please contact us immediately.

Support

For help with questions, suggestions, or problems, please contact us