1. 本机生成ssh密钥对
ssh-keygen -t rsa
2. 把本机公钥添加到服务器文件~/.ssh/authorized_keys末尾
cat ~/.ssh/id_rsa.pub
3. 本机使用私钥即可登陆服务器
ssh -i ~/.ssh/id_rsa root@192.168.1.12
4. 使用paramiko实现,key文件使用的是
#!/usr/bin/env python3
import paramiko
key = paramiko.RSAKey.from_private_key_file("/home/test/.ssh/id_rsa")
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
print("connecting")
ssh.connect(hostname="192.168.1.12", username="root", pkey=key)
print("connected")
commands = "uname -a"
stdin, stdout, stderr = ssh.exec_command(commands)
stdin.close()
res, err= stdout.read(), stderr.read()
result= res if res else err
print(result)
ssh.close()