Paramiko — using encrypted private key file on OS X

前端 未结 3 651
天命终不由人
天命终不由人 2021-02-07 05:10

I\'m trying to use Paramiko to connect to an SSH server from Python. This is what I tried so far:

>>> import paramiko
>>> import os
>>>         


        
3条回答
  •  不要未来只要你来
    2021-02-07 05:29

    The following approach seems to work fine (on OS X, with the usual setup of encrypted private keys that have passphrases stored in the keychain, without any user interaction):

    import paramiko
    
    ssh = paramiko.SSHClient()
    ssh.load_system_host_keys()
    ssh.connect(HOST, username=USER, look_for_keys=False)
    ...
    ssh.close()
    

    It seems that look_for_keys=False is not absolutely necessary. However, if you use it you will get much better error messages in the case of an authentication failure ("AuthenticationException" instead of "PasswordRequiredException").


    If you really want to use private keys directly, you could do the following:

    import os
    import paramiko
    import keyring
    
    keyfile = os.path.expanduser('~/.ssh/id_rsa')
    password = keyring.get_password('SSH', keyfile)
    key = paramiko.RSAKey.from_private_key_file(keyfile, password=password)
    

    However, based on my testing, this is not needed. The above solution that uses ssh.connect in a straightforward manner should be sufficient.

提交回复
热议问题