Python 容器问题

Python container troubles

基本上我想做的是在服务器上使用 Python 生成一个 json SSH 密钥列表(public 和私有)。我正在使用嵌套词典,虽然它在一定程度上可以工作,但问题在于它显示了所有其他用户的键;我需要它为每个用户只列出属于该用户的密钥。

下面是我的代码:

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的输出中。我可能完全错了,所以欢迎任何指点。

感谢您的回复,我阅读了嵌套词典,发现关于这个 post 的最佳答案帮助我解决了问题:What is the best way to implement nested dictionaries?

我简化了代码,现在只有一本字典,而不是所有的字典。这是工作代码:

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