Just a little script to ssh-add known keys for a ssh connection automatically when needed
#!/usr/bin/env perl # # use strict; use warnings; use Fatal qw(:void open close); sub read_ssh_config { my $config_file = shift || $ENV{HOME}."/.ssh/config"; die "Cannot open config file: $!" if ! -r $config_file; open my $fh, "<", $config_file; my %ssh_config = (); my $current_host = undef; while (<$fh>) { next if /^\s*$/ || /^\s*#/; if (/^\s*Host\s+(\S+)\s*$/) { $current_host = $1; $ssh_config{$current_host} = {}; } elsif (/^\s*(\S+)\s+(\S+)\s*$/) { if (defined $current_host) { $ssh_config{$current_host}{$1} = $2; } else { die "Syntax error in SSH config file at line $.: $!"; } } else { + die "Syntax error in SSH config file at line $.: $!"; + } } close $fh; return %ssh_config; } sub all_known_keys { return map( (split(/\s+/, $_))[2], split(/\n/, `/usr/bin/ssh-add -l` +) ); } sub get_hostname_from_arguments { foreach my $argument (@ARGV) { if ($argument =~ m/--/) { last; } elsif ($argument !~ /^-.*/) { return $argument; } } return 0; } my $ssh_host = get_hostname_from_arguments(); my %ssh_config = read_ssh_config(); my $used_key = glob($ssh_config{$ssh_host}{"IdentityFile"}); my @known_keys = all_known_keys(); if (defined $used_key) { if (! grep(/$used_key/, @known_keys)) { system("/usr/bin/ssh-add", "-t", "1800", $used_key) == 0 or die "Cannot add key $used_key: $!"; } } system("/usr/bin/ssh", @ARGV); __END__
[download]