X-Git-Url: http://git.iain.cx/?p=profile.git;a=blobdiff_plain;f=kill_known_host;h=46dbb8395fcbf5c393eb46abe8eeff7da4592296;hp=acc638530a141f40b6b393a9e5cd7be7ea372841;hb=518d9698777610c32b50ac83d8a9463be91f0563;hpb=756cfebbb2ef97127f5d5c0ff2254c1e16441d9b diff --git a/kill_known_host b/kill_known_host index acc6385..46dbb83 100755 --- a/kill_known_host +++ b/kill_known_host @@ -3,21 +3,32 @@ # $Id$ # # kill_known_host: Remove an entry from the ssh hosts file. -# Usage: kill_known_host -# kill_known_host +# Usage: kill_known_host [options] | +# Options: -n Only report key; don't delete it. +# -p Allow partial match. +# Example: kill_known_host -p www +# Remove all keys with hostname beginning www. # Exits: 0 on success. # 1 on error. # 111 if the entry didn't exist. # Notes: Based on Jim's kill-known-host. # +use Getopt::Std; + my $KNOWN_HOSTS = "$ENV{HOME}/.ssh/known_hosts"; my $SCRATCH = "$KNOWN_HOSTS.$$"; +our $opt_n, $opt_p; +getopts("np"); + # Check args. unless (@ARGV) { - print STDERR "Usage: kill_known_host \n"; - print STDERR "Usage: kill_known_host \n"; + print STDERR "Usage: kill_known_host [options] |\n"; + print STDERR "Options: -n Only report key; don't delete it.\n"; + print STDERR " -p Allow partial match.\n"; + print STDERR "Example: kill_known_host -p www\n"; + print STDERR " Remove all keys with hostname beginning www.\n"; print STDERR "Exits: 0 on success.\n"; print STDERR " 1 on error.\n"; print STDERR " 111 if the entry didn't exist.\n"; @@ -25,33 +36,46 @@ unless (@ARGV) { } my $host = shift; +my $dotstar = $opt_p ? '[^\s,]*' : ''; my $re; # Check if it's an IP or a hostname. if ($host =~ /^[1-9]\d{0,2}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/) { - $re = "^([^\\s]+,)?$host\\s"; + $re = "^([^\\s]+,)?$host$dotstar\\s"; } else { - $re = "^$host\\s"; + $re = "^$host$dotstar\[\\s,]"; } # Read known hosts. open IN, "< $KNOWN_HOSTS" or die "Can't read known_hosts: $!\n"; # Open scratch file. -open OUT, "> $SCRATCH" or die "Can't open scratch file: $!\n"; +open OUT, "> $SCRATCH" or die "Can't open scratch file: $!\n" unless $opt_n; my ($in, $out) = (0, 0); while () { $in++; - next if /$re/; - print OUT; - $out++; + if (/$re/) { + if ($opt_n) { + $out++; + print; + } + else { next } + } + unless ($opt_n) { + print OUT; + $out++; + } } # Cleanup. -close OUT; close IN; +if ($opt_n) { + exit 111 unless $out; + exit 0; +} +close OUT; # Move hosts. rename $SCRATCH, $KNOWN_HOSTS or die "Can't rename $KNOWN_HOSTS: $!\n";