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的輸出。我可能會完全錯誤的,所以任何指針都歡迎。
你應該問一個關於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';) –