Skip to content

Instantly share code, notes, and snippets.

@friek
Created October 29, 2015 09:44
Show Gist options
  • Select an option

  • Save friek/0c44e58b9fbb120eab5e to your computer and use it in GitHub Desktop.

Select an option

Save friek/0c44e58b9fbb120eab5e to your computer and use it in GitHub Desktop.
Script to remove an entry from the ssh known hosts file
#!/bin/bash -e
line_num="$1"
if [ -z "$line_num" ]; then
echo "Usage: $0 <line num>"
exit 1
fi
known_hosts="${HOME}/.ssh/known_hosts"
tmp_file="${known_hosts}.$$"
trap "rm -f $tmp_file" EXIT
# Sanity checks
if [ -O "${known_hosts}" ]; then
echo "File $known_hosts does not exists or is not owned by you"
exit 1
fi
num_lines=`wc -l $known_hosts | awk '{print $1}'`
if [ "$line_num" -gt "$num_lines" ]; then
echo "Line number $line_num exceeds the number of lines ($num_lines) in $known_hosts"
exit 1
fi
# Regenerate the known hosts file
(head -`expr ${line_num} - 1` "${known_hosts}" ; tail -`expr ${num_lines} - ${line_num}` ${known_hosts}) > "$tmp_file"
mv "$tmp_file" "$known_hosts"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment