Perl password access script

jesterj
2006-11-17
2012-09-17
  • jesterj
    jesterj
    2006-11-17

    Here is a small perl script for accessing password from a version 3 database on my Linux box. This is meant to tide me over till the SWT version handles the new database format.

    fyi: To get this script to work you have to install the CPAN modules 'Crypt::Pwsafe' and 'Clipboard'. I also had to install the xclip package on my Ubuntu box. Finally, I had to change a line in the Clipboard library file called Xclip.pm:

    * On line 27 the all_selections list should contain 'clip-board' not clipboard.
    * On line 28 the index number should be 2 not 0.
    

    Enjoy.

    !/usr/bin/env perl

    use strict;
    use Crypt::Pwsafe;
    use Clipboard;

    listpw.pl - List the contents of a Password Safe v3 database, and copy

    the password to the clipboard.

    Usage:

    listpw.pl database_file search_pattern [index_number]

    listpw.pl lists all the entries in the database that match the pattern.

    If only one entry matches the pattern, or an index_number is given, then

    the password is copied to the clipboard.

    - database_file should be a passwordsafe version 3 format

    - search_pattern is a perl regular expression pattern without the delimiters. The search iscase insensitive.

    - index_number is optional, to retrieve a given password from the list generated for the given search_pattern.

    Feel free to use this script however you want. There are no license nor copyright restricitions.

    my $file = shift;
    my $pattern = shift;
    my $entry_num = shift;
    die "File not found.\n" unless $file && -f $file;
    my $comb = Crypt::Pwsafe::enter_combination();
    my $pwsafe = new Crypt::Pwsafe $file, $comb;
    my $result_cnt = 0;
    my @pwd;
    print "\n\n";
    foreach my $group (keys %$pwsafe) {
    my $gh = $pwsafe->{$group};
    foreach my $entry (keys %$gh) {
    if ($entry =~ /$pattern/i) {
    (my $login, my $name) = split(/@/, $entry);
    ++$result_cnt;
    print "-----\n\n" if $result_cnt > 1;
    print "$result_cnt: $name\n";
    print " Login: $login\n";
    my $eh = $gh->{$entry};
    print " URL: $eh->{'URL'}\n";
    $pwd[$result_cnt] = $eh->{'Password'};
    }
    }
    }

    Copy the password if there is only one entry found.

    if ($result_cnt == 1 or $entry_num) {
    my $k = 1;
    $k = $entry_num if ($entry_num > 0 and $result_cnt > 0);
    print "\nPassword for entry $k copied to the clipboard.\n\n";
    Clipboard->copy($pwd[$k]);
    } else {
    print "\nNo password copied for multiple results\n\n";
    }