Don't show from localhost.
[profile.git] / kill_known_host
1 #!/usr/bin/perl
2 #
3 # $Id$
4 #
5 # kill_known_host: Remove an entry from the ssh hosts file.
6 # Usage: kill_known_host [options] <IP>|<hostname>
7 # Options: -n   Only report key; don't delete it.
8 #          -p   Allow partial match.
9 # Example: kill_known_host -p www
10 #          Remove all keys with hostname beginning www.
11 # Exits:   0 on success.
12 #          1 on error.
13 #        111 if the entry didn't exist.
14 # Notes: Based on Jim's kill-known-host.
15 #
16
17 use Getopt::Std;
18
19 my $KNOWN_HOSTS = "$ENV{HOME}/.ssh/known_hosts";
20 my $SCRATCH = "$KNOWN_HOSTS.$$";
21
22 our $opt_n, $opt_p;
23 getopts("np");
24
25 # Check args.
26 unless (@ARGV) {
27   print STDERR "Usage: kill_known_host [options] <IP>|<hostname>\n";
28   print STDERR "Options: -n   Only report key; don't delete it.\n";
29   print STDERR "         -p   Allow partial match.\n";
30   print STDERR "Example: kill_known_host -p www\n";
31   print STDERR "         Remove all keys with hostname beginning www.\n";
32   print STDERR "Exits:   0 on success.\n";
33   print STDERR "         1 on error.\n";
34   print STDERR "       111 if the entry didn't exist.\n";
35   exit 1;
36 }
37
38 my $host = shift;
39 my $dotstar = $opt_p ? '[^\s,]*' : '';
40 my $re;
41
42 # Check if it's an IP or a hostname.
43 if ($host =~ /^[1-9]\d{0,2}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/) {
44   $re = "^([^\\s]+,)?$host$dotstar\\s";
45 }
46 else {
47   $re = "^$host$dotstar\[\\s,]";
48 }
49
50 # Read known hosts.
51 open IN, "< $KNOWN_HOSTS" or die "Can't read known_hosts: $!\n";
52
53 # Open scratch file.
54 open OUT, "> $SCRATCH" or die "Can't open scratch file: $!\n" unless $opt_n;
55
56 my ($in, $out) = (0, 0);
57 while (<IN>) {
58   $in++;
59   if (/$re/) {
60     if ($opt_n) {
61       $out++;
62       print;
63     }
64     else { next }
65   }
66   unless ($opt_n) {
67     print OUT;
68     $out++;
69   }
70 }
71
72 # Cleanup.
73 close IN;
74 if ($opt_n) {
75   exit 111 unless $out;
76   exit 0;
77 }
78 close OUT;
79
80 # Move hosts.
81 rename $SCRATCH, $KNOWN_HOSTS or die "Can't rename $KNOWN_HOSTS: $!\n";
82
83 exit 111 if $in == $out;
84 exit 0;