Python容器问题

时间:2017-04-07 21:48:20

标签: python ssh-keys

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

以下是我的代码:

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的输出中。我可能会对此完全错误,所以欢迎提出任何指示。

1 个答案:

答案 0 :(得分:0)

感谢您的回复,我读了嵌套词典,发现这篇文章的最佳答案帮助我解决了这个问题: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