paramiko
原文链接: paramiko
- content
{:toc}
简介
paramiko 是一个可以模拟 SSH 的 Python 包,在登陆成功后可以进行 执行命令、上传文件、下载文件 等操作。
- 要求 Python 2.6+/3.3+
- 不支持文件夹上传,可遍历实现
安装
只尝试了 pip 安装:
sudo pip install paramiko
测试
>>> import paramiko
>>>
使用
执行命令
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect("IP",22,"用户名", "密码")
stdin, stdout, stderr = ssh.exec_command("命令")
print stdout.readlines()
ssh.close()
上传文件
import paramiko
t = paramiko.Transport(("IP",22))
t.connect(username = "用户名", password = "密码")
sftp = paramiko.SFTPClient.from_transport(t)
remotepath='/tmp/test.txt'
localpath='/tmp/test.txt'
sftp.put(localpath,remotepath)
t.close()
下载文件
import paramiko
t = paramiko.Transport(("IP",22))
t.connect(username = "用户名", password = "密码")
sftp = paramiko.SFTPClient.from_transport(t)
remotepath='/tmp/test.txt'
localpath='/tmp/test.txt'
sftp.get(remotepath, localpath)
t.close()
上传文件夹
import paramiko,os
def upload(local_dir,remote_dir):
try:
t=paramiko.Transport(("IP",22))
t.connect(username="用户名",password="密码")
sftp=paramiko.SFTPClient.from_transport(t)
if(not local_dir.endswith(os.sep)):
local_dir = local_dir + os.sep
for root,dirs,files in os.walk(local_dir):
for filespath in files:
local_file = os.path.join(root,filespath)
a = local_file.replace(local_dir,'')
remote_file = os.path.join(remote_dir,a)
try:
sftp.put(local_file,remote_file)
except Exception,e:
sftp.mkdir(os.path.split(remote_file)[0])
sftp.put(local_file,remote_file)
for name in dirs:
local_path = os.path.join(root,name)
a = local_path.replace(local_dir,'')
remote_path = os.path.join(remote_dir,a)
try:
sftp.mkdir(remote_path)
except Exception,e:
print e
t.close()
except Exception,e:
print e