python-sshpubkeys icon indicating copy to clipboard operation
python-sshpubkeys copied to clipboard

Read/write AuthorizedKeysFile

Open mpounsett opened this issue 3 years ago • 4 comments
trafficstars

It would be helpful to also be able to write the contents of an AuthorizedKeysFile instance out to disk, in addition to parsing authorized_keys. This probably wouldn't involve too much refactoring of the class.

mpounsett avatar Mar 10 '22 12:03 mpounsett

What would be the usecase for this?

To me, it sounds like a better idea to write whatever data was used as a source when loading authorized_keys to this library. If this library would allow modifying key options, then writing would definitely make sense.

ojarva avatar Mar 12 '22 08:03 ojarva

The use case would be for writing code that manages the contents of authorized keys files. So, load an authorized_keys file into an instance of the class, replace one or more keys, then write the file out again.

The class wouldn't necessarily need to do file management itself, but it could have a to_str() method or something that could be redirected to a file.

mpounsett avatar Mar 12 '22 16:03 mpounsett

I threw together an example of what I'm talking about at mpounsett/python-sshpubkeys@34b8d7c75f4cfa6ac9029bbc71ac57883e783fff

Usage would look something like this (using StringIO in place of a real file):

import io
from sshpubkeys import AuthorizedKeysFile
from tests.valid_keys import keys

# slice 3 keys off the top of the test keys
authorized_keys = "\n".join([x[0] for x in keys][:3])
f = io.StringIO(authorized_keys)
key_file = AuthorizedKeysFile(f, strict=False)
# modify the key list here
f.seek(0)
f.write(str(key_file))
f.seek(0)
print(f.read())

If you really wanted to get fancy, AuthorizedKeysFile could be reimplemented as a context manager, allowing automatic writes to take place on close.

with open(keyfile, mode='w') as f:
   with AuthorizedKeysFile(f, strict=False) as key_list:
      key_list.append(SSHKey(...))

mpounsett avatar Mar 12 '22 17:03 mpounsett

Any news on that? It could be quite useful for me.

tuxiqae avatar Oct 27 '22 15:10 tuxiqae