Showing posts with label Perl. Show all posts
Showing posts with label Perl. Show all posts

2018-09-26

Perl one-liners

I think Perl one-liners are still super useful. They are small Perl programs that are run directly from command line. Like this one from the Kubernetes job documentation:

perl -Mbignum=bpi -wle 'print bpi(2000)' # calculate PI to 2000 digits

perl is the Perl language interpreter. -M and -wle are command line switches (or flags or options) that modify the perl’s behaviour. See below for explanation of what they mean. The string within the quotes is the Perl code that gets executed. In this case it uses the bpi subroutine from the bignum module to calculate the PI with accuracy of 2000 digits. The command will take a while to finish.

Switches

These are some of the most used command line switches:

  • -e '<code>' – execute <code>
  • -E '<code>' – Execute <code> enabling new features for your version of Perl
  • -w – enable warnings (generally advisable)
  • -p – loop through lines, reading and printing them (in-script equivalent: while (<>) { [<code>] print })
  • -n – loop through lines, reading but not printing them
  • -l – print a newline ($/ actually) after each line of output and chomp input newlines if used with -n or -p
  • -i[<.ext>] – edit files in-place, optionally create backups with <.ext> extension
  • -a – autosplit the $_ default variable into @F array (space is the default separator, change it with -F, ex. -F:)
  • -M<module>[=<subroutine>,...] – load subroutine(s) from a Module

See perlrun for more.

Cut

Cut out 2nd and 1st space separated field (column):

$ cat birthdays.txt
2890-09-22 Bilbo Baggins
2968-09-22 Frodo Baggins
$ perl -wlane 'print join " ", @F[1,0]' birthdays.txt
Bilbo 2890-09-22
Frodo 2968-09-22

The field numbering starts at 0. We use join to put a space between the cut out fields.

Find lines in logs that contain error or warning:

perl -wne '/error|warning/i && print' /var/log/*.log

The thing between slashes is a regular expression. It means match string error or string warning anywhere in the log line. i says to Perl to ignore the case. So it will match ERROR, error, Warning etc. If the regex finds a match (i.e. evaluates to true) the && logical operator runs the print statement that will print the line containing the match.

Get IP addresses from logs:

journalctl --since "00:00" | perl -wlne '/((?:\d{1,3}\.){3}\d{1,3})/ && print $1' | \
sort | uniq > /tmp/ips.txt

The IP address regex explained:

(               # capturing parenthesis to be retrieved via $1
    (?:         # non capturing parenthesis, only for grouping
        \d{1,3} # one to three decimal numbers
        \.      # literal dot
    ){3}        # three times all within innermost parenthesis
        \d{1,3} # one to three decimal numbers
)               

For a more serious program where you want to cover possible edge cases you should use a well tested module Regexp::Common as suggested by PerlMonks.

Replace

Replace /bin/sh with /bin/bash and emit the transformed passwd file to STDOUT:

perl -wpe 's#/bin/sh$#/bin/bash#' /etc/passwd

We used # instead of / as delimeter for better readibility since the strings themselves contain slashes. $ means end of the string.

Replace colour with color in all text files. The original files will be kept with .bak suffix:

perl -i.bak -wpe 's/colour/color/g' *.txt

g (global) means replace all occurences in a string not just the first one.

Convert between DOS and Unix newline:

perl -i -wpe 's/\r//'  <file1> <file2> ... # dos-to-unix
perl -i -wpe 's/$/\r/' <file1> <file2> ... # unix-to-dos

Calculate

Calculate the total size of log files older than 30 days:

find /opt/splunk/syslog/ -iname "*log*" -type f -mtime +30 | \
perl -wlne '$sum += (stat)[7]}{print $sum'

The stat function returns a 13-element list of status info about a file. We take the 8th element (with index 7) which is the size of a file. We loop over the found files and add the size of each into the $sum variable. The handy Eskimo Greeting Operator is for printing the $sum when the loop is over (suggested by PerlMonks).

More

perl1line.txt

For a deeper dive see Famous Perl One-Liners Explained. If you want a book have a look at Minimal Perl for UNIX and Linux People.

2016-10-17

Creating a Module::Build Distribution

(Up-to-date source of this post.)

Creating a Module::Build Distribution

We show here how to create a Perl distribution using Module::Build build system with Module::Starter. The other Perl build system (we don't show here) is ExtUtils::MakeMaker. For sophisticated distribution creation see Dist::Zilla.

Create config file ~/.module-starter/config:

author: Foo Bar
email: foo@bar.org
builder: Module::Build
verbose: 1
# Allow adding new modules to existing distro.
plugins: Module::Starter::AddModule

... or use module-starter (see below) with command line arguments like:

--author="Foo Bar" \
--email=foo@bar.org \
--mb \
--verbose \
--plugin=Module::Starter::AddModule

Run basic commands

  • install needed modules: cpanm Module::Build Module::Starter Module::Starter::AddModule
  • create (a working skeleton of) module distribution: module-starter --module=Animal
  • change to the created distro directory: cd Animal
  • create the Build script: perl Build.PL
  • build the distro (modules from lib copied to blib staging area and embedded documenation translated into Unix manpage in blib/libdoc): ./Build
  • make sure the tests pass: ./Build test (or run individual tests - see below)
  • test the distro: ./Build disttest
  • create the distro: ./Build dist

Add modules

  • add new modules: module-starter --module=Sheep,Cow,Horse --dist=Animal
  • add new modules (we are inside our distribution directory): module-starter --module=Sheep,Cow,Horse --dist=.

Run individual tests

  • rebuild distro and run test including modules from blib/lib: ./Build && perl -Iblib/lib -T t/Cow.t
  • rebuild distro and run test including modules from blib/lib: ./Build && perl -Mblib -T t/Cow.t

Measure out test coverage

  • run testcover target: ./Build testcover
  • turn the collected statistics into human-readable reports: cover

The following is a typical release cycle for github users:

  1. Work on changes until all tests pass
  2. Make sure the Changes file documents all major changes
  3. Make your changes atomic, all changes related to a particular fix or feature should go in a single commit, including the Changes entry.
  4. Bump the version
  5. Upload to PAUSE
  6. Tag with the version. By convention for version 1.01 the tag would be 'v1.01'
  7. Push to github

For more see:

2016-09-12

Finding a Good CPAN Module

(Up-to-date source of this post.)

Anyone can contribute to CPAN. It is also pretty huge. This means you might want to separate the wheat from the chaff. To do that these hints might help:

  1. What's the code activity? The more the better.

  2. How many issues do we have? The open bugs show community involvement, the closed ones are about the maintainer's diligence.

  3. What aboout the quality and quantity of tests and their results.

  4. Are there any reverse dependencies (they use the same basic principle as Google PageRank)? The more the better.

  5. Follow the advice of experts in the Perl field, ex. Task::Kensho.

NOTE: don't check any of the hints above in isolation but all/more of them together.

Resources:

  • https://www.usenix.org/system/files/login/articles/logindec1410_blank-edelman.pdf

2015-12-22

Testing a Perl Script

(Up-to-date source of this post.)

At $work, I was to upgrade several Debians from Squeezy through Wheezy to Jessie (6 to 8). I wanted to be sure that after the upgrade (mostly) the same processes are running as before. I whipped up a script, that simply stores the list of running processes before the upgrade. When run subsequently it reports missing processes (if any).

To make the script reliable and easy to maintain I wanted to test it somehow. To do that I turned the script into a modulino following brian d foy's advice in chapter 17 of Mastering Perl. The trick was to put all the code into subroutines that can be tested and using the caller() function to decide whether the script is used as a script or as a module. The script looks something like this now:

#!/usr/bin/env perl
use strict;
use warnings;
use 5.010;
use autodie;
use Getopt::Long;
use Pod::Usage;
use Storable qw(freeze thaw);

GetOptions(
    "h|?|help"  => \my $help,
    "l|print"   => \my $print,
    "v|verbose" => \my $verbose,
    "n|net"     => \my $net,
) or pod2usage(1);
pod2usage( -exitval => 0, -verbose => 2, -noperldoc => 1 ) if $help;

run() unless caller();

sub run {
    # code
}

sub missing_procs {
    # code
}

sub get_procs {
    # code
}

After this modification I created a symlink

ln -s checkprocs checkprocs.pm 

and wrote a couple of tests in checkprocs.t

use strict;
use warnings;
use Test::More tests => 3;

use_ok('checkprocs');

#<<<
my $old = [(
    'proc1',
    '/path/to/proc2',
    'proc3',
    'proc4 --with-arg',
    '/path/to/proc5 -w',
)];
my $new = [(
    'proc1',
    'proc3',
    '/path/to/proc5'
)];
#>>>

{
    my @missing_procs = main::missing_procs( $old, $new );
    is(
        "@missing_procs",
        '/path/to/proc2 proc4',
        'Found missing process w/o args'
    );
}

{
    my @missing_procs = main::missing_procs( $old, $new, { verbose => 1 } );
    is(
        "@missing_procs",
        '/path/to/proc2 proc4 --with-arg',
        'Found missing process w/ args'
    );
}

Since I need to run the script under different Perl versions (Squeeze had 5.10.1, Wheezy 5.15.2 and Jessie 5.20.2) I used perlbrew to test it:

$ perlbrew exec prove checkprocs.t
perl-5.10.1
==========
checkprocs.t .. ok
All tests successful.
Files=1, Tests=3,  0 wallclock secs ( 0.01 usr  0.00 sys +  0.04 cusr  0.00 csys =  0.05 CPU)
Result: PASS

perl-5.14.2
==========
checkprocs.t .. ok
All tests successful.
Files=1, Tests=3,  0 wallclock secs ( 0.01 usr  0.00 sys +  0.04 cusr  0.00 csys =  0.05 CPU)
Result: PASS

perl-5.20.2
==========
checkprocs.t .. ok
All tests successful.
Files=1, Tests=3,  0 wallclock secs ( 0.01 usr  0.00 sys +  0.03 cusr  0.00 csys =  0.04 CPU)
Result: PASS

2015-07-13

My First CPAN Contribution

Last week I uploaded App::Monport to CPAN. I did it to try out the CPAN toolchain and to get a feeling of accomplishment :-). But I also think the application might be useful for some folks.

Update: My application was mentioned in PerlTricks' article. Cool!

2015-01-22

Scan and Compare Versions of Your Network Services

One of the most effective, although often neglected, ways to keep your servers secure are regular updates of running services (daemons). If you are running more than one server, it might be useful to compare the version of the services running on the hosts. If you find any differences you should consider upgrading to the newest version.

To achieve this, we are going to use the extremely useful scanning tool called nmap. We will call it and parse its output from a Perl script using Nmap::Parser module.

Here goes the script:

#!/usr/bin/perl
use strict;
use warnings;
use Nmap::Parser;

die "Usage: $0 host1 [host2 host3 ...]\n" unless @ARGV;

listNetServices(@ARGV);

=head2 listNetServices( @hosts )

Are we running different versions of network services (ex. SSH) on different
hosts? Useful for identifying unpatched (old) versions of network services but
we have to include a host with patched services into @hosts.

=cut

sub listNetServices {
    my @hosts = @_;

    my $services;    # HoH

    # Anonymous subroutine
    my $nmap = sub {
        my $host = shift;    #Nmap::Parser::Host object, just parsed

        for my $port ( $host->tcp_ports('open') ) {

            # Nmap::Parser::Host::Service object
            my $svc = $host->tcp_service($port);

            my $service = join( ' | ',
                $svc->name    // '',
                $svc->product // '',
                $svc->version // '' );

            push @{ $services->{$port}{$service} },
              $host->hostname . ' (' . $host->addr . ')';

        }
    };

    my $np = new Nmap::Parser;
    $np->callback($nmap);
    $np->parsescan( '/usr/bin/nmap', '-sV', @hosts );

    # Print report
    for my $port ( sort keys %$services ) {

        my $n_versions = keys %{ $services->{$port} };
        next unless $n_versions > 1;

        print "$port - $n_versions different versions on this port\n";

        for my $version ( sort keys %{ $services->{$port} } ) {
            print ' ' x 4 . $version . "\n";
            for my $host ( sort @{ $services->{$port}{$version} } ) {
                print ' ' x 8 . $host . "\n";
            }
        }
    }

    return;
}

(Up-to-date source of the ListNetServices function can be found in MyUtils.)

And this is a sample output suggesting that host1 is running older versions of both ssh and http daemons:

$ perl script-listed-above host1 host2
22 - 2 different versions on this port
    ssh | OpenSSH | 5.5p1 Debian 6+squeeze5
        host1 (1.2.3.4)
    ssh | OpenSSH | 6.7
        host2 (5.6.7.8)
80 - 2 different versions on this port
    http | Apache httpd | 2.2.16
        host1 (1.2.3.4)
    http | Apache httpd | 2.4.10
        host2 (5.6.7.8)

2014-10-31

Shell Completion

(Up-to-date source of this post. First version created 2013-03-12)

Bash (one of the most popular shells) offers a great feature that makes many people's Tab key pretty worn. It completes the names of commands, directories and files you start to write. The complete command (man bash => "Programmable Completion") lets users extend the standard completion fucntion.

Bash Completion

The Bash Completion project offers many many completion rules that you can add to ~/.bashrc. If not already installed:

aptitude install bash-completion

Then you may need to source it from /etc/bashrc or ~/.bashrc:

# Use bash-completion, if available
[[ $PS1 && -f /usr/share/bash-completion/bash_completion ]] && \
    . /usr/share/bash-completion/bash_completion

Debian does this for you via /etc/bash.bashrc.

Try it out by typing:

ssh [TAB]

If you don't get any meaningful results add some of your hosts into ~/.ssh/config and try again:

host login.example.org
host bigserver.example.net

If you have ssh keys deployed one the remote hosts, try out:

scp bigserver.example.net:[TAB]

Bash Completion with Perl

Bash completion project builds on shell scripting which is easy to write but limited. You might prefer to use a more complete language, like Perl.

Perl Programs

If you want your Perl applications to complete their options use Getopt::Complete module:

#!/usr/bin/perl -w
# getopt-complete -- sample self-completing script
use strict;

use Getopt::Complete(
    'tmpdir' => [ "/tmp",     "$ENV{HOME}/temp", "/var/tmp" ],
    'user'   => [ $ENV{USER}, "root" ],
);

Add the following to ~/.bashrc:

function _getopt_complete () {
    COMPREPLY=($( COMP_CWORD=$COMP_CWORD perl `which ${COMP_WORDS[0]}` ${COMP_WORDS[@]:0} ));
}
complete -F _getopt_complete getopt-complete

Then source ~/.bashrc or relogin and run:

./getopt-complete <TAB>

Compiled Programs

In case you want to add the completion functionality to a compiled program you can't rewrite, you have to wrap it into an external helper, like Mike Schilli did in github-helper. If you want to use this script, put it into your PATH and add following to ~/.bashrc:

complete -C github-helper -o default git

The -o default option reverts to shell's completion mechanism if github-helper has nothing to offer.

2014-09-09

Unix Times and Perl

(Up-to-date source of this post.)

Unix filesystem consists of two parts:

  • data blocks - contents of files and directories (special files with inode-name pairs)
  • index to those data blocks

Entries in the index are called inodes (index nodes). Inodes contain medatada (data about data) on the files, like:

  • pointer to the data blocks
  • type of thing it represents (directory, file, etc.)
  • size of the thing
  • "mode" of the thing (nine permissions bits + three bits that primarily affect the operation of executables)
  • info on owner and group

There is also a time information among the metadata. Actually three types of them:

.----------------------------------------------------------------------------------------------------.
| Type        | Short name | ls option | Description                                                 |
+-------------+------------+-----------+-------------------------------------------------------------+
| Access Time | atime      | -ult      | when file was last accessed (read)                          |
| Modify Time | mtime      | -lt       | when the actual contents of the file were last modified     |
| Change Time | ctime      | -cl       | when the inode information (the metadata) was last modified |
'-------------+------------+-----------+-------------------------------------------------------------'

Using timestamps

To get information about a file (actually about its inode) run the shell command stat or find:

  • find /home/webservice/backups/ -mtime +5 -exec rm -f {} \; -- will delete any file with content that had not changed for 5 days from now.
  • find /home/webservice/backups/ -ctime +5 -exec rm -f {} \; -- will delete any file that has been untouched for 5 days.

Getting time info with Perl

To access an inode from within Perl, use:

1. stat function (returns pretty much everything that the underlying stat Unix system call returns):

my($atime, $mtime, $ctime) = (stat($filename))[8,9,10] or die "Couldn't stat '$filename': $!";

.. $atime, $mtime, and $ctime -- The three timestamps represented in the system's timestamp format: a 32-bit number telling how many seconds have passed since the ''Epoch'', an arbitrary starting point for measuring system time (it's the beginning of 1970 at midnight Universal Time on Unix systems).

2. File::stat:

use File::stat;

my $inode = stat("/bin/ls");
my $ctime = $inode->ctime;
my $size  = $inode->size;

3. -X operators, modeled on the shell's test operators:

my @original_files = qw/ file1 file2 file2 /;  # in practice - read from the FS using a glob or directory handle
my @big_old_files;                             # files we want to put on backup tapes
foreach my $filename (@original_files) {
    push @big_old_files, $filename             
      if -s $filename > 100_000 and -A _ > 90; # -X operators cache value returned by stat(2); access it via _
}

Changing timestamps with Perl

In those rare cases when you want to lie to other programs about when a file was most recently accessed (atime) or modified (mtime), use the utime function:

my $atime = time;                 # now
my $mtime = $time - 24 * 60 * 60; # one day (86400 secs) ago
utime $atime, $mtime, glob "*";   # set access to now, mod to a day ago

.. the third timestamp (ctime) is always set to "now" whenever anything alters a file - there's no way to set it with utime

.. the primary purpose of ctime is for incremental backups - if the file's ctime is newer that the date on the backup tape, it's time to back it up again

Sources

  • Perl Cookbook
  • ULSAH

2014-07-04

Benchmarking Perl Code

(Up-to-date source of this post.)

Sometimes my code takes a really long time to run and I'd like to know which of the alternatives runs faster.

In this example I compare two sorting subroutines; a "naive" approach and "The Schwartzian Transform". The former subroutine just compares all files' sizes to each other while the latter first precomputes the size of each file and then does the comparisons.

use Benchmark qw(timethese);

chdir;    # change to my home directory
my @files = glob '*';

timethese(
    -2,
    {
        naive => sub {
            my @sorted = sort { -s $a <=> -s $b } @files;
        },
        schwartzian => sub {
            my @sorted =
              map  { $_->[0] }
              sort { $a->[1] <=> $b->[1] }
              map  { [ $_, -s $_ ] } @files;
        },
    }
);

The program's output:

Benchmark: running naive, schwartzian for at least 2 CPU seconds...
     naive:  2 wallclock secs ( 0.58 usr +  1.49 sys =  2.07 CPU) @ 11661.84/s (n=24140)
schwartzian:  2 wallclock secs ( 1.57 usr +  0.59 sys =  2.16 CPU) @ 21200.00/s (n=45792)

The output says that the Schwartzian Transform is much faster (the function ran more times in 2 seconds). The reason is that we don't ask for the file size each time we want to compare two files sizes; we ask just once for each file size.

See Also

  • http://perldoc.perl.org/Benchmark.html
  • Intermediate Perl, 2nd, p. 144
  • http://www.perlmonks.com/?node_id=393128

2013-12-27

Debugging Perl Scripts

(Up-to-date source of this post.)

When there's a problem while writing a Perl program the thing I do often is to print out the contents of a variable. There are two ways I usually do it.

If the the variable is not complex (i.e. it's a simple scalar, array or hash variable) I use the print function:
#!/usr/bin/perl
use strict;
use warnings;

# A number between 1 and 100 (both included)
my $secret = int( 1 + rand 100 );

# If DEBUG environment variable set, print out the secret number
print "The secret number is $secret"
    if $ENV{DEBUG};
Then I just set the environment variable while running the script:
$ DEBUG=1 ./script.pl
The secret number is 3
In case I'm dealing with a more complicated data structure, like the $server variable below, I use Data::Dumper (which outputs valid Perl code):
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;

my $name = 'foo';

my $server = {
    'server' => {
        'imageRef'  => '8a3a9f96-b997-46fd-b7a8-a9e740796ffd',
        'flavorRef' => '2',
        'name'      => $name,
        'metadata'  => { 'My Server Name' => 'Ubuntu 12.10 (Quantal Quetzal)' },
    }
};

print Dumper $server;

The Perl Debugger

Sometimes I need something more than just printing out the variable contents. In that case I reach for the Perl debugger:
$ perl -d prog.pl
It shows each line of code before it executes it. The most common commands are these:
  • h -- help
  • s -- single-step the program
  • x -- dump a variable value (for complex data use x \%href or even x sort keys %hash)
  • n -- step over a subroutine
  • q -- quit the debugger
To have the command line history within the Perl debugger, you need to install:
  • Debian/Ubuntu packages: libncurses-dev libreadline-dev
  • Perl module: Term::ReadLine::Gnu

More