您的位置:首页 > 运维架构

[迎风奔雨] [自动化运维脚本] paramiko 基于ssh实现文件上传和下载

2017-08-23 22:48 561 查看
#coding=utf-8
import paramiko,datetime,os,re
import zipfile
hostname='192.168.177.128'
username='root'
password='root'
port=22
def upload(local_dir,remote_dir):
try:
t=paramiko.Transport((hostname,port))
t.connect(username=username,password=password)
sftp=paramiko.SFTPClient.from_transport(t)
#这里判断一下传入路径是单个文件还是一个目录,如果是目录就整个目录上传,如果是
#单个文件就只上传单个文件。
if os.path.isfile(local_dir):
remote_file = os.path.join(remote_dir,os.path.split(local_dir)[1])
try:
sftp.put(local_dir,remote_file)
except Exception,e:
print e
print "upload sigle file %s to remote %s" % (local_dir,remote_file)
else :
#获取上传目录名称,同时对目录进行打包,因为上传目录速度最快的方法就是把目录打包,单个文件批量传输速度太慢。
print "zip file start :%s" % datetime.datetime.now()
uploadDirName = os.path.split(local_dir)[1]
zipf = zipfile.ZipFile(uploadDirName+'.zip', 'w')
pre_len = len(os.path.dirname(local_dir))
for root,dirs,files in os.walk(local_dir):
try:
# print root
for filename in files:
pathfile = os.path.join(root, filename)
arcname = pathfile[pre_len:].strip(os.path.sep)   #相对路径
zipf.write(pathfile, arcname)
# print "write %s to %s" % (pathfile, arcname)
except Exception,e:
print e
zipf.close()
#上传文件到远程服务器
try:
if os.path.exists(uploadDirName+'.zip'):
remote_file = os.path.join(remote_dir,uploadDirName+'.zip')
local_file = uploadDirName+'.zip'
sftp.put(local_file,remote_file)
except Exception,e:
print e
print 'upload file success %s ' % datetime.datetime.now()
t.close()
#开始远程执行解压缩命令,同时删除上传的zip包
s= paramiko.SSHClient()
s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
s.connect('192.168.177.128','22','root', 'root')
commands = r'unzip -o %s -d remote_dir ;rm -f %s' % (remote_file,local_file)
stdin,stdout,stderr=s.exec_command(commands)
print stdout.read()
s.close()
except Exception,e:
print e
if __name__=='__main__':
local_dir=r'C:\Program Files\360'
remote_dir='/opt/'
upload(local_dir,remote_dir)
报错No suitable address family for 192.168.177.128
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: