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

#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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值