paramiko模块
通过ssh2协议远程登录服务器执行命令或上传下载文件
ssh 公钥密钥连接
RSA -非对称密钥验证
公钥 public key
私钥 private key
10.0.0.31 ----> 10.0.0.41
私钥 公钥
10.0.0.31先生成一对公钥和私钥,将公钥给要被登录的机器
ssh-keygen生成一对公钥私钥,id_rsa.pub公钥,id_rsa私钥
将公钥放到.ssh/authorized_keys下面
ssh-copy-id "-p52113 [email protected]"
基于账号密码的形式,执行命令或上传下载文件
import paramiko # 基于账号密码执行命令 # 创建SSH对象 ssh = paramiko.SSHClient() # 允许连接不在know_hosts文件中的机器 ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # 连接服务器 ssh.connect(hostname="192.168.80.20", port=22, username="root", password="[email protected]") # 执行命令 stdin, stdout, stderr = ssh.exec_command("free -m") # 获取命令结果 res, err = stdout.read(), stderr.read() result = res if res else err print(result.decode()) # 关闭连接 ssh.close() # 基于账号密码的上传下载 transport = paramiko.Transport(("192.168.80.20", 22)) transport.connect(username="root", password="[email protected]") sftp = paramiko.SFTPClient.from_transport(transport) # 将location.py上传至服务器的/tmp/test.py sftp.put("高级FTP.png", "/root/高级FTP.png") # 将remove_path下载到本地local_path sftp.get("remove_path", "local_path") transport.close() # SSHClient 封装 Transport transport = paramiko.Transport((‘hostname‘, 22)) transport.connect(username=‘wupeiqi‘, password=‘123‘) ssh = paramiko.SSHClient() ssh._transport = transport stdin, stdout, stderr = ssh.exec_command(‘df‘) print(stdout.read().decode()) transport.close()
基于密钥的形式,执行命令或上传下载文件
import paramiko # 基于密钥执行命令 private_key = paramiko.RSAKey.from_private_key_file("id_rsa") ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(hostname="192.168.80.24", port=22, username="root", pkey=private_key) stdin, stdout, stderr = ssh.exec_command("ifconfig") res, err = stdout.read(), stderr.read() result = res if res else err print(result.decode()) ssh.close() # 基于密钥的上传下载 private_key = paramiko.RSAKey.from_private_key_file("id_rsa") transport = paramiko.Transport(("192.168.80.24", 22)) transport.connect(username="root", pkey=private_key) sftp = paramiko.SFTPClient.from_transport(transport) sftp.get("test.txt", "1") transport.close() # SSHClient 封装 Transport private_key = paramiko.RSAKey.from_private_key_file(‘/home/auto/.ssh/id_rsa‘) transport = paramiko.Transport((‘hostname‘, 22)) transport.connect(username=‘wupeiqi‘, pkey=private_key) ssh = paramiko.SSHClient() ssh._transport = transport stdin, stdout, stderr = ssh.exec_command(‘df‘) transport.close()
时间: 2024-10-11 05:51:14