acc638530a141f40b6b393a9e5cd7be7ea372841
[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 <IP>
7 #        kill_known_host <hostname>
8 # Exits:   0 on success.
9 #          1 on error.
10 #        111 if the entry didn't exist.
11 # Notes: Based on Jim's kill-known-host.
12 #
13
14 my $KNOWN_HOSTS = "$ENV{HOME}/.ssh/known_hosts";
15 my $SCRATCH = "$KNOWN_HOSTS.$$";
16
17 # Check args.
18 unless (@ARGV) {
19   print STDERR "Usage: kill_known_host <IP>\n";
20   print STDERR "Usage: kill_known_host <hostname>\n";
21   print STDERR "Exits:   0 on success.\n";
22   print STDERR "         1 on error.\n";
23   print STDERR "       111 if the entry didn't exist.\n";
24   exit 1;
25 }
26
27 my $host = shift;
28 my $re;
29
30 # Check if it's an IP or a hostname.
31 if ($host =~ /^[1-9]\d{0,2}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/) {
32   $re = "^([^\\s]+,)?$host\\s";
33 }
34 else {
35   $re = "^$host\\s";
36 }
37
38 # Read known hosts.
39 open IN, "< $KNOWN_HOSTS" or die "Can't read known_hosts: $!\n";
40
41 # Open scratch file.
42 open OUT, "> $SCRATCH" or die "Can't open scratch file: $!\n";
43
44 my ($in, $out) = (0, 0);
45 while (<IN>) {
46   $in++;
47   next if /$re/;
48   print OUT;
49   $out++;
50 }
51
52 # Cleanup.
53 close OUT;
54 close IN;
55
56 # Move hosts.
57 rename $SCRATCH, $KNOWN_HOSTS or die "Can't rename $KNOWN_HOSTS: $!\n";
58
59 exit 111 if $in == $out;
60 exit 0;