arbelt
10/20/2017 - 8:18 AM

Simple script to fetch SSH keys from Github

Simple script to fetch SSH keys from Github

#!/usr/bin/env perl

use v5.20;
use autodie;
#use HTTP::Tiny;

#my $agent = HTTP::Tiny->new(
    #default_headers => { 'Accept' => 'application/json' }
#);

#my $response = $agent->get('https://github.com/arbelt.keys');

#print $response->{content};

my $auth_keys_file = "$ENV{HOME}/.ssh/authorized_keys";

#-r $auth_keys_file or die "File $auth_keys_file cannot be read.";

#if (! -r $auth_keys_file) { warn "$auth_keys_file does not exist..." }

my @current_keys;

sub get_current_keys {
    no autodie;
    open my $fh, "<", $auth_keys_file;
    chomp(my @keys = grep { !m/Github/ } <$fh>);
    close $fh; 
    return @keys;
}

my @current_keys = &get_current_keys;

my %keys;
foreach (@current_keys) { 
    $_ = s/(\S+)\s+(\S+).*/$1 $2/r ;
    $keys{$_}++; } 

print STDERR "Fetching keys from Github...\n";
chomp(my @gh_keys = `curl -s https://github.com/arbelt.keys`);

my @new_keys = map { $_ . " Github" }
    grep { !$keys{$_} }
    @gh_keys;

print STDERR "Adding ", scalar @new_keys, " new keys...\n";

my @all_keys = (@current_keys, @new_keys);

open my $fh, ">", $auth_keys_file;
foreach (@all_keys) { print $fh $_, "\n" }
close $fh;