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