I got a little bit bored a short while ago and decided I hadn’t written anything in Perl for quite some time, I wasn’t too sure of what to write so I decided to write a small; and very simple script to gather some server metrics for my home media server here.
I’d like to point out at this stage the Perl script I am about to present is short, simple and not tested for security issues so while it will probably work fine, I provide no warranty or indicate that it is fit for any purpose at all, what so ever.
I’ve gone back over the code in order to completely comment it so it should make perfect sense to someone with little to no programming experience, although it is so simple they are more than likely not required.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | #!/usr/bin/perl use Socket; #global variables my $port = shift || 9876; #What port the app will listen on my $protocol = getprotobyname('tcp'); #What protocol to use (tcp/udp) my $client; #Open a socket to listen for incoming connections socket(SOCKET, PF_INET, SOCK_STREAM, $proto) or die "Cant open socket $!n"; #Set a flag on the socket to be reusable, I.E. when it's closed, it automatically re-opens. setsockopt(SOCKET, SOL_SOCKET, SO_REUSEADDR, 1) or die "Can't set socket option to reusable $!n"; #bind the socket to the port we want bind(SOCKET, pack('Sn4x8', AF_INET, $port, "")) or die "Can't bind to port: $portn"; #Start listening listen(SOCKET, 5) or die "Unable to listen on port $portn"; #Inform the user that the script is ready to accept connections print "Server started on port $port"; #wait for a connection while($client = accept(NET_SOCKET, SOCKET)) { #send the user the information we're looking for... print "Opening connection ---->;n"; #The following block grabs all of the information to present to the socket my $statistics = "n"; $statistics .= `cat /proc/cpuinfo`; #Take the output of /proc/cpuinfo $statistics .= "nnnn"; $statistics .= `df -h`; #Get the free disk space. $statistics .= "nnnn"; $statistics .= `who`; #See who is logged in. $statistics .= "nnnn"; $statistics .= `ps x`; #Grab a copy of some of the processes $statistics .= "nnn"; #Send the gathered information to the socket print NET_SOCKET "$statisticsn"; #Close the socket close NET_SOCKET; print "Closing connection <----n"; } #Wait for more connections, keep going until the script is terminated. |