ungleich-cli/ungleich_ssh_key.py

50 lines
1.9 KiB
Python
Raw Normal View History

2019-06-08 17:10:08 +00:00
#!/usr/bin/env python3
import os
import sys
import subprocess
class SSHKey(object):
def __init__(self, parser, parents):
self.parser = parser
self.parser['sshkey'] = self.parser['sub'].add_parser(
'sshkey',
help="Manage SSH keys",
parents=[parents])
self.parser['sshkey'].add_argument('--user',
help='Username on the host',
required=False,
default="root")
self.parser['sshkey'].add_argument('--key',
help='Name of the key',
required=True)
self.parser['sshkey'].add_argument('--key-dir',
help='Directory holding keys',
default=os.path.join(os.environ['HOME'], "vcs/ungleich-ssh-keys/"),
required=false)
self.parser['sshkey'].add_argument('--host',
help='Host to use',
required=True)
self.parser['sshkey'].add_argument('--delete',
help='Delete key instead of adding',
action="store_true")
self.parser['sshkey'].set_defaults(func=self._manage_key)
def _manage_key(self, args):
if args.delete:
print("Not yet supported to delete, sorry :-)")
sys.exit(1)
keyfile = os.path.join(args.keydir, "{}.pub".format(args.key))
if not os.path.exists(keyfile):
print("Key for {} does not exist in {}. Aborting".format(args.key, args.keydir))
sys.exit(1)
cmd = 'cat {} | ssh {} "mkdir -p ~/.ssh; cat >> ~/.ssh/authorized_keys"'.format(keyfile, args.host)
subprocess.run(cmd, shell=True)