Remove a line from known hosts with single command

No more going into the file and deleting the entry manually.
To remove line 123 from ~/.ssh/known_hosts:

Usage

rmknownhost 123

Code
Put this it into a file called rmknownhost inside a folder that is in your PATH and chmod +x the file.

#! /usr/bin/env ruby
line = ARGV[0] || raise("gimme line to remove")
hosts = File.expand_path("~/.ssh/known_hosts")
content = File.readlines(hosts)
removed = content.delete_at line.to_i - 1
puts "Removed:\n#{removed}"
File.open(hosts, 'w'){|f| f.write content * ""}

4 thoughts on “Remove a line from known hosts with single command

  1. wow thats short šŸ˜€

    the “Removed: xxx” message is missing but thats not that important.
    Its a bit cryptic, wrapping it into a function would be good…

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s