ssh keys - Python container troubles -
basically trying generate json list of ssh keys (public , private) on server using python. using nested dictionaries , while work extent, issue lies displaying every other user's keys; need list keys belong user each user.
below code:
def ssh_key_info(key_files): f in key_files: c_time = os.path.getctime(f) # gets creation time of file (f) username_list = f.split('/') # splits on / character user = username_list[2] # assigns 2nd field frome above spilt user variable key_length_cmd = check_output(['ssh-keygen','-l','-f', f]) # run ssh-keygen command on file (f) attr_dict = {} attr_dict['date created'] = str(datetime.datetime.fromtimestamp(c_time)) # converts file create time string attr_dict['key_length]'] = key_length_cmd[0:5] # assigns first 5 characters of key_length_cmd variable ssh_user_key_dict[f] = attr_dict user_dict['ssh_keys'] = ssh_user_key_dict main_dict[user] = user_dict a list containing absolute path of keys (/home/user/.ssh/id_rsa example) passed function. below example of receive:
{ "user1": { "ssh_keys": { "/home/user1/.ssh/id_rsa": { "date created": "2017-03-09 01:03:20.995862", "key_length]": "2048 " }, "/home/user2/.ssh/id_rsa": { "date created": "2017-03-09 01:03:21.457867", "key_length]": "2048 " }, "/home/user2/.ssh/id_rsa.pub": { "date created": "2017-03-09 01:03:21.423867", "key_length]": "2048 " }, "/home/user1/.ssh/id_rsa.pub": { "date created": "2017-03-09 01:03:20.956862", "key_length]": "2048 " } } }, as can seen, user2's key files included in user1's output. may going wrong, pointers welcomed.
thanks replies, read on nested dictionaries , found best answer on post, helped me solve issue: what best way implement nested dictionaries?
instead of dictionaries, simplfied code , have 1 dictionary now. working code:
class vividict(dict): def __missing__(self, key): # sets , return new instance value = self[key] = type(self)() # retain local pointer value return value # faster return dict lookup main_dict = vividict() def ssh_key_info(key_files): f in key_files: c_time = os.path.getctime(f) username_list = f.split('/') user = username_list[2] key_bit_cmd = check_output(['ssh-keygen','-l','-f', f]) date_created = str(datetime.datetime.fromtimestamp(c_time)) key_type = key_bit_cmd[-5:-2] key_bits = key_bit_cmd[0:5] main_dict[user]['ssh keys'][f]['date created'] = date_created main_dict[user]['ssh keys'][f]['key type'] = key_type main_dict[user]['ssh keys'][f]['bits'] = key_bits
Comments
Post a Comment