【发布时间】:2017-09-03 09:28:48
【问题描述】:
基本上,我要做的是使用 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 的输出中。我可能完全错了,所以欢迎任何指针。
【问题讨论】:
-
你应该问一个关于 Python 容器的通用问题 - 我相信大多数人只是跳过这个,因为他们不了解 SSH 密钥。虽然您的问题实际上与 SSH 主机密钥无关。这是一个非常简单的 Python 问题。
-
函数的临界点是
ssh_user_key_dict[f] = attr_dict。这就是为每次迭代创建一个新密钥的地方。 (第一个键是“/home/user1/.ssh/id_rsa”)。接下来的两个步骤只是不断地重新分配user_dict['SSH_Keys']和main_dict[user]。我猜你有user2和 3 个SSH_Keys;)