Paramiko的使用
来自CloudWiki
Paramiko的使用
安装
pip instsll paramiko
基于用户名和密码的SSHClient方式登录
# -*- coding: utf-8 -*- # File Name: paramiko_user_pwd.py # Description: 使用用户名密码来登陆并执行远程命令 import paramiko # 建立一个sshclient对象 ssh = paramiko.SSHClient() # 将信任的主机自动加入到host_allow列表,须放在connect方法前面 ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # 调用connect方法连接服务器 ssh.connect(hostname="192.168.1.3", port=22, username="root", password="000000") # 执行命令 stdin, stdout, stderr = ssh.exec_command("echo `date` && df -hl") # 结果放到stdout中,如果有错误将放到stderr中 print(stdout.read().decode('utf-8')) # returncode = stdout.channel.recv_exit_status() print("returncode:",returncode) # 关闭连接 ssh.close()
基于用户名和密码的Transport方式登录并实现上传与下载
# -*- coding: utf-8 -*- #Time: 2018/8/23 22:07:12 #Description: 实现上传和下载功能 #File Name: transport_upload_download.py import paramiko trans = paramiko.Transport(('192.168.1.3', 22)) # 建立连接,指定SSHClient的_transport trans.connect(username='root', password='000000') ssh = paramiko.SSHClient() ssh._transport = trans # 执行命令,和传统方法一样 stdin, stdout, stderr = ssh.exec_command('echo `date` && df -hl') print(stdout.read().decode('utf-8')) # 实例化一个 sftp对象,指定连接的通道 sftp = paramiko.SFTPClient.from_transport(trans) # 发送文件 sftp.put(localpath='./transport_upload_download.py', remotepath='/tmp/transport_upload_download_tmp.py') # 下载文件 sftp.get(localpath='./tmp/transport_upload_download.py', remotepath='/tmp/transport_upload_download_tmp.py') stdin, stdout, stderr = ssh.exec_command('ls -ltr /tmp') print(stdout.read().decode('utf-8')) # 关闭连接 trans.close()