2017-04-07 1 views
1

기본적으로 내가하려는 것은 파이썬을 사용하는 서버에서 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 " 
     } 
    } 
}, 

에서 볼 수있는 바와 같이 , 사용자 2의 키 파일이 사용자 1의 출력에 포함되어 있습니다. 나는 이것을 완전히 잘못 생각할지도 모른다. 그래서 어떤 조언도 환영 받는다. 답장에 대한

+0

파이썬 컨테이너에 대한 일반적인 질문을해야합니다. 저는 대부분의 사람들이 SSH 키에 대한 지식이 없으므로이 코드를 무시한다고 생각합니다. 귀하의 질문은 실제로는 SSH 호스트 키와 관련이 없습니다. 그것은 꽤 사소한 파이썬 질문입니다. –

+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 
관련 문제