paramiko
一 介绍
二 通过用户名密码方式远程执行命令
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=‘192.168.16.85‘, port=22, username=‘root‘, password=‘123456‘)
stdin, stdout, stderr = ssh.exec_command(‘df‘)
result = stdout.read()
ssh.close()
print(result.decode(‘utf-8‘))
三 通过用户名密码方式上传下载文件
import paramiko
transport = paramiko.Transport((‘192.168.16.85‘, 22))
transport.connect(username=‘root‘, password=‘123456‘)
sftp = paramiko.SFTPClient.from_transport(transport)
sftp.get(‘/data/123.txt‘, ‘123.txt‘)
transport.close()
四 通过公钥私钥远程执行命令
import paramiko
private_key = paramiko.RSAKey.from_private_key_file(r‘C:/Users/Administrator/.ssh/id_rsa‘)
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=‘192.168.16.85‘, port=22, username=‘root‘, pkey=private_key)
stdin, stdout, stderr = ssh.exec_command(‘df‘)
result = stdout.read()
ssh.close()
print(result)
五 通过公钥私钥远程上传下载文件
import paramiko
private_key = paramiko.RSAKey.from_private_key_file(r‘C:/Users/Administrator/.ssh/id_rsa‘)
transport = paramiko.Transport((‘192.168.16.85‘, 22))
transport.connect(username=‘root‘, pkey=private_key)
sftp = paramiko.SFTPClient.from_transport(transport)
transport.close()
六 通过私钥字符串远程连接服务器
key = """-----BEGIN RSA PRIVATE KEY-----
-----END RSA PRIVATE KEY-----"""
import paramiko
from io import StringIO
private_key = paramiko.RSAKey(file_obj=StringIO(key))
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=‘192.168.16.85‘, port=22, username=‘root‘, pkey=private_key)
stdin, stdout, stderr = ssh.exec_command(‘df‘)
result = stdout.read()
ssh.close()
print(result)
七 生成公钥私钥并上传
sh-keygen.exe -m pem
ssh-copy-id -i ~/.ssh/id_rsa.pub root@192.168.16.85
ssh root@192.168.16.85