Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Path: blob/master/src/scripts/ssh_host_keys_freeze.py
Views: 687
#!/usr/bin/env python31# coding: utf82# Author: Harald Schilly <[email protected]>3# Copyright: GPL34"""5When a server in the GCE environment is started with a new IP and a new instance ID,6the host SSH keys in /etc/ssh are recreated.7That's in general a nice security feature, but this also happens when the instance type8changes (some scripts can change pre-empt to non-pre-empt boxes causing this, etc.).910This script hardcodes the current four /etc/ssh/ key-pairs in a config file for cloud-init.11This cloud-init is part of Ubuntu and managing a couple of things in the VM (hostname, network, etc.)12The generated config file then contains the key-pairs and on each boot they are used for writing13the keys.1415So, the output in `/etc/cloud/cloud.cfg.d/99-smc.cfg` is like:1617```18ssh_keys:19dsa_private: |20-----BEGIN DSA PRIVATE KEY-----21MIIBugIBAAKBgQD…22…23…24-----END DSA PRIVATE KEY-----2526dsa_public: "ssh-dss AAA………"27```2829Documentation:30http://cloudinit.readthedocs.org/en/latest/index.html31"""32import sys33import os34from os.path import join, basename, dirname, exists35from glob import glob36from pwd import getpwnam3738out_fn = '/etc/cloud/cloud.cfg.d/99-smc.cfg'3940try:41import yaml42except:43print(44"ERROR: I need yaml for python3, i.e. sudo apt-get install -y python3-yaml"45)46sys.exit(1)474849class literal(str):50pass515253def literal_presenter(dumper, data):54return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='|')555657yaml.add_representer(literal, literal_presenter)585960def main():61# hold key data, dict for key_type_public/key_type_private for each key_type62keys = {}6364for key_fn in glob('/etc/ssh/ssh_host_*_key'):65key_type = basename(key_fn)[9:-4]66print("Reading key {}".format(key_type))67priv = open(key_fn).read()68publ = open(key_fn + ".pub").read()69keys[key_type + '_private'] = literal(priv)70keys[key_type + '_public'] = publ7172out = yaml.dump({"ssh_keys": keys}, default_flow_style=False, width=10000)73# print(out)7475if not exists(dirname(out_fn)):76raise Exception(77"Directory for {} does not exist. Are the clout-init utils installed?".78format(out_fn))7980open(out_fn, 'w').write(out)81root = getpwnam("root")82os.chown(out_fn, root.pw_uid, root.pw_gid)83os.chmod(out_fn, 0o600)848586if __name__ == '__main__':87try:88main()89except IOError as e:90raise e91print("You need to be root or prefix this with sudo")929394