模块paramiko,使用密钥文件ssh登录

Circle / 2024-10-29 / 原文

1. 不用密码,使用密钥文件登录
import paramiko

#指定私钥位置
private_key = paramiko.RSAKey.from_private_key_file("/root/.ssh/id_rsa")
#创建ssh对象
ssh = paramiko.SSHClient()
# 允许连接不在know_hosts文件
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy)

#连接服务器
ssh.connect(hostname="47.121.131.108", port=22, username="root", pkey=private_key)

# 执行命令(输入结果 输出结果,错误结果)
stdin, stdout, stderr = ssh.exec_command("cdwe")

#获取结果
#result = stdout.read()
#print(result.decode())

res, err = stdout.read(), stderr.read()
result = res if res else err
print(result.decode())
#关闭连接
ssh.close()


2.ssh-copy-id工具
将本机的公钥复制到远程主机的 ~/.ssh/authorized_keys 文件中
ssh-copy-id user@remote_host