~/.ssh/authorized_keys file format can be briefly summarised as
- a text file with one line per key;
- empty lines and lines beginning with the octothorpe (
#) are ignored;
- there are four fields: options, keytype, key and comment;
- fields one and four are optional;
- field one may contain whitespace if double-quoted;
- field four may contain whitespace without being quoted.
The full description is in
Is there a reliable, scriptable (e.g.
bash), way to manipulate keys in the
~/.ssh/authorized_keys file ?
For example, a script might:
- extract a specific key (being the keytype, key and comment fields),
- manipulate (add, modify or remove) the options field,
- manipulate (add, modify or remove) the comment field,
- iterate over all keys, or
- remove a key.
There does not appear to be a SSH tool (e.g.
ssh-add &c.) capable of modifying the
~/.ssh.authorized_keys file, and the nature of the options and comment fields make this very difficult to reliably achieve using the usual
perl -pe approach.
Following comments, here is a simplified problem: imagine a script that reads the
~/.ssh/authorized_keys file and outputs all keys - only the keys: no options and no blank or comment lines.
I struggled to do this because each row is space-delimited but:
- the options can contain whitespace or be absent altogether, and
- the comments, due to whitespace, can be zero or more fields.
Therefore you have no idea how many fields that a row contains, and you can't easily tell how many of those fields the options spans.
You'd need a overly-complex regex that understands the scope of the options field so that it could remove it reliably before outputting the rest of the line. I tried to do this with
A contrived use-case for such a script would be to list the fingerprints of all keys.