天天看點

paramiko 基于密鑰檔案登陸

首先密鑰登陸遠端的原理

client 端 将公鑰放在遠端機器authorized_keys:

使用 ssh-copy-id  app@ip

接着在client機器生成密鑰 使用ssh-keygen -t  rsa 生成密鑰對,id_rsa:

編寫測試腳本:

import paramiko
hostname="192.168.110.131"
port=22
username="app"
#client ssh-keygen -t rsa 生成的id_rsa 私鑰
pkey_path="/home/app/.ssh/id_rsa"
private = paramiko.RSAKey.from_private_key_file(pkey_path)
paramiko.util.log_to_file('paramiko.log')  
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(hostname,port,username,pkey=private)
stdin, stdout, stderr = client.exec_command('df -h ')
print(stdout.read().decode('utf-8'))