2017-04-07 86 views
1

基本上我想要做的是在使用Python的服务器上生成一个json的SSH密钥列表(公共和私有)。我使用嵌套字典,虽然它在一定程度上有效,但问题在于它显示每个其他用户的密钥;我需要它仅列出属于每个用户的用户的密钥。Python容器麻烦

下面是我的代码:

def ssh_key_info(key_files): 
    for f in key_files: 
      c_time = os.path.getctime(f) # gets the creation time of file (f) 
      username_list = f.split('/') # splits on the/character 
      user = username_list[2] # assigns the 2nd field frome the above spilt to the user variable 

      key_length_cmd = check_output(['ssh-keygen','-l','-f', f]) # Run the ssh-keygen command on the file (f) 

      attr_dict = {} 
      attr_dict['Date Created'] = str(datetime.datetime.fromtimestamp(c_time)) # converts file create time to string 
      attr_dict['Key_Length]'] = key_length_cmd[0:5] # assigns the first 5 characters of the key_length_cmd variable 

      ssh_user_key_dict[f] = attr_dict 
      user_dict['SSH_Keys'] = ssh_user_key_dict 
      main_dict[user] = user_dict 

甲包含密钥的绝对路径(/home/user/.ssh/id_rsa例如)列表被传递给函数。下面是我收到一个例子:

{ 
"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 " 
     } 
    } 
}, 

可以看出,user2的密钥文件都包含在user1的输出。我可能会完全错误的,所以任何指针都欢迎。

+0

你应该问一个关于Python容器的通用问题 - 我相信大多数人只是略过了这个,因为他们没有关于SSH密钥的知识。虽然你的问题实际上与SSH主机密钥无关。这是非常简单的Python问题。 –

+0

函数的关键点是'ssh_user_key_dict [f] = attr_dict'。这就是为每个迭代创建一个新密钥的地方。 (第一个键是“/home/user1/.ssh/id_rsa”)。接下来的两个步骤只是不断重新赋值user_dict ['SSH_Keys']'和'main_dict [user]'。我猜你有'user2'和3个'SSH_Keys';) –

回答

0

感谢您的答复,我对嵌套的字典阅读后,发现对这个职位的最佳答案,帮我解决这个问题:What is the best way to implement nested dictionaries?

而是所有的词典,我simplfied代码,只是有一个字典现在。这是工作代码:

class Vividict(dict): 
    def __missing__(self, key):   # Sets and return a new instance 
     value = self[key] = type(self)() # retain local pointer to value 
     return value      # faster to return than dict lookup 

main_dict = Vividict() 

def ssh_key_info(key_files): 
      for 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