22
33import configparser
44import os
5+ import stat
56import subprocess
67
78
89SNAP_COMMON = os .environ ['SNAP_COMMON' ]
910SETTINGS_FILE = "settings.ini"
1011
12+ KEY_DIR_NAME = "keys"
13+ PRIVATE_KEY_FILE = "node.key"
14+ PUBLIC_KEY_FILE = "node.pub"
15+
1116# List of settings to apply. Each item is a tuple:
1217# (snap option, ini section, name).
1318#
@@ -33,7 +38,29 @@ SETTINGS = [
3338]
3439
3540
36- if __name__ == "__main__" :
41+ def prepare_ssh_key ():
42+ key_dir = os .path .join (SNAP_COMMON , KEY_DIR_NAME )
43+ if not os .path .isdir (key_dir ):
44+ os .mkdir (key_dir )
45+
46+ private_key_path = os .path .join (key_dir , PRIVATE_KEY_FILE )
47+ if not os .path .isfile (private_key_path ):
48+ cmd = ["openssl" , "genrsa" , "-out" , private_key_path , "4096" ]
49+ subprocess .call (cmd )
50+
51+ os .chmod (private_key_path , stat .S_IRUSR )
52+
53+ public_key_path = os .path .join (key_dir , PUBLIC_KEY_FILE )
54+ if not os .path .isfile (public_key_path ):
55+ cmd = ["ssh-keygen" , "-y" , "-f" , private_key_path ]
56+ result = subprocess .check_output (cmd )
57+ pubkey = result .decode ('ascii' , 'ignore' ).strip ()
58+
59+ with open (public_key_path , "w" ) as output :
60+ output .write (pubkey )
61+
62+
63+ def prepare_settings_file ():
3764 path = os .path .join (SNAP_COMMON , SETTINGS_FILE )
3865
3966 config = configparser .ConfigParser ()
@@ -50,7 +77,8 @@ if __name__ == "__main__":
5077 result = subprocess .check_output (cmd )
5178 if len (result ) > 0 :
5279 value = result .decode ('ascii' , 'ignore' ).strip ()
53- config .set (section , name , value )
80+ if len (value ) > 0 :
81+ config .set (section , name , value )
5482 except subprocess .CalledProcessError :
5583 pass
5684
@@ -65,3 +93,8 @@ if __name__ == "__main__":
6593 config .write (output )
6694 except OSError as error :
6795 print (error )
96+
97+
98+ if __name__ == "__main__" :
99+ prepare_ssh_key ()
100+ prepare_settings_file ()
0 commit comments