juliet070 2015-06-12 08:29 采纳率: 100%
浏览 2040
已采纳

sftp.py ,python基础语法

#!/usr/bin/env python

-----------------------------------------------------------------------------

sftp.py

Author: Andyrat

Date: 2014/01/07 09:39:38

import sys
import os
import time

try:
from paramiko import SSHClient
from paramiko import AutoAddPolicy
except e:
print 'Error:Need module paramiko,TRY:apt-get install python-paramiko.'

#------- modify here ----------------------------------------------

download file from this server

serFr = {'ip':'10.13.20.5','port':3322,'username':'admin','password':'P@ssword',
'rdirname':'/U12/Andy/0802/', # remote dir path
'ldirname':'./h0802/', # local dir path
}

upload file to this server

serTo = {'ip':'10.13.20.5','port':3322,'username':'admin','password':'P@ssword',
'rdirname':'/U12/Andy/0803/', # remote dir path
'ldirname':'./h0802/', # local dir path
}
#------------------------------------------------------------------

class FTPSync:
def init(self,host):
'''connect to server'''
self.server = host
self.ssh = SSHClient()
self.ssh.set_missing_host_key_policy(AutoAddPolicy())

def login(self):
    self.ssh.connect(self.server['ip'],self.server['port'],self.server['username'],self.server['password'],allow_agent=False)
    self.sftp = self.ssh.open_sftp()

def get_file(self,ftp_path,local_path='.'):
    self.sftp.get(ftp_path,local_path)

def put_file(self,local_path,ftp_path='.'):
    self.sftp.put(local_path,ftp_path)

def get_dir(self,ftp_path,local_path='.',begin=True):
    ftp_path = ftp_path.rstrip('/')
    if self._is_ftp_dir(ftp_path):
        if begin:
            if os.path.isdir(local_path):
                self._rm_loc_dir(local_path)
            else:
                os.makedirs(local_path)
            local_path = os.path.join(local_path,os.path.basename(ftp_path))

        if not os.path.isdir(local_path):
            os.makedirs(local_path)

        self._cd_ftp_dir(ftp_path)
        ftp_files = self._get_ftp_filelst()
        for afile in ftp_files:
            local_file = os.path.join(local_path,afile)

            if self._is_ftp_dir(afile):
                self.get_dir(afile,local_file,False)
            else:
                self.get_file(afile,local_file)
        self._cd_ftp_dir('..')
        return
    else:
        print 'ERROR:The dir:%s is not exist' %ftp_path
        return

def put_dir(self,local_path,ftp_path,begin=True):
    ftp_path = ftp_path.rstrip('/')
    if os.path.isdir(local_path):
        if begin:
            if self._is_ftp_dir(ftp_path):
                self._rm_ftp_dir(ftp_path)
            else:
                self._mk_ftp_dir(ftp_path)
            ftp_path = os.path.join(ftp_path,os.path.basename(local_path))

        if not self._is_ftp_dir(ftp_path):
            self._mk_ftp_dir(ftp_path)

        os.chdir(local_path)
        local_files = os.listdir('.')
        for afile in local_files:
            if os.path.isdir(afile):
                new_ftp_path = os.path.join(ftp_path,afile)
                self.put_dir(afile,new_ftp_path,False)
            else:
                self.put_file(afile,os.path.join(ftp_path,afile))
        os.chdir('..')
        return
    else:
        print 'ERROR:The dir:%s is not exist' %local_path
        return

def close(self):
    self.sftp.close()

def _is_ftp_dir(self,path):
    try:
        attr = self.sftp.lstat(path)
        attr = str(attr)
        if attr.startswith('d'):
            return True
        else:
            return False
    except:
        return False

def _rm_ftp_dir(self,ftp_path):
    ftp_path = ftp_path.rstrip('/')
    if self._is_ftp_dir(ftp_path):
        self._cd_ftp_dir(ftp_path)
        ftp_files = self._get_ftp_filelst()
        for afile in ftp_files:
            if self._is_ftp_dir(afile):
                self._rm_ftp_dir(afile)
            else:
                #print 'sftp.remove:',afile
                self.sftp.remove(afile)
        self._cd_ftp_dir('..')
        #print 'sftp.rmdir:',ftp_path
        self.sftp.rmdir(ftp_path)
        return

def _rm_loc_dir(self,Dir):
    if os.path.isdir( Dir ):
        paths = os.listdir( Dir )
        for path in paths:
            filePath = os.path.join( Dir, path )
            if os.path.isfile( filePath ):
                os.remove( filePath )
            elif os.path.isdir( filePath ):
                self._rm_loc_dir(filePath)

def _cd_ftp_dir(self,path):
    self.sftp.chdir(path)

def _get_ftp_filelst(self):
    return self.sftp.listdir()

def _mk_ftp_dir(self,path):
    self.sftp.mkdir(path)

if name == '__main__':

ser1 = FTPSync(serFr)
ser1.login()
ser1.get_dir(serFr['rdirname'],serFr['ldirname'])
ser1.close()

ser2 = FTPSync(serTo)
ser2.login()
ser2.put_dir(serTo['ldirname'],serTo['rdirname'])
ser2.close()
  • 写回答

3条回答 默认 最新

  • juliet070 2015-06-12 08:33
    关注

    #!/usr/bin/env python

    -----------------------------------------------------------------------------

    sftp.py

    Author: Andyrat

    Date: 2014/01/07 09:39:38

    import sys
    import os
    import time

    try:
    from paramiko import SSHClient
    from paramiko import AutoAddPolicy
    except e:
    print 'Error:Need module paramiko,TRY:apt-get install python-paramiko.'

    #------- modify here ----------------------------------------------

    download file from this server

    serFr = {'ip':'10.13.20.5','port':3322,'username':'admin','password':'P@ssword',
    'rdirname':'/U12/Andy/0802/', # remote dir path
    'ldirname':'./h0802/', # local dir path
    }

    upload file to this server

    serTo = {'ip':'10.13.20.5','port':3322,'username':'admin','password':'P@ssword',
    'rdirname':'/U12/Andy/0803/', # remote dir path
    'ldirname':'./h0802/', # local dir path
    }
    #------------------------------------------------------------------

    class FTPSync:
    def init(self,host):
    '''connect to server'''
    self.server = host
    self.ssh = SSHClient()
    self.ssh.set_missing_host_key_policy(AutoAddPolicy())

    def login(self):
        self.ssh.connect(self.server['ip'],self.server['port'],self.server['username'],self.server['password'],allow_agent=False)
        self.sftp = self.ssh.open_sftp()
    
    def get_file(self,ftp_path,local_path='.'):
        self.sftp.get(ftp_path,local_path)
    
    def put_file(self,local_path,ftp_path='.'):
        self.sftp.put(local_path,ftp_path)
    
    def get_dir(self,ftp_path,local_path='.',begin=True):
        ftp_path = ftp_path.rstrip('/')
        if self._is_ftp_dir(ftp_path):
            if begin:
                if os.path.isdir(local_path):
                    self._rm_loc_dir(local_path)
                else:
                    os.makedirs(local_path)
                local_path = os.path.join(local_path,os.path.basename(ftp_path))
    
            if not os.path.isdir(local_path):
                os.makedirs(local_path)
    
            self._cd_ftp_dir(ftp_path)
            ftp_files = self._get_ftp_filelst()
            for afile in ftp_files:
                local_file = os.path.join(local_path,afile)
    
                if self._is_ftp_dir(afile):
                    self.get_dir(afile,local_file,False)
                else:
                    self.get_file(afile,local_file)
            self._cd_ftp_dir('..')
            return
        else:
            print 'ERROR:The dir:%s is not exist' %ftp_path
            return
    
    def put_dir(self,local_path,ftp_path,begin=True):
        ftp_path = ftp_path.rstrip('/')
        if os.path.isdir(local_path):
            if begin:
                if self._is_ftp_dir(ftp_path):
                    self._rm_ftp_dir(ftp_path)
                else:
                    self._mk_ftp_dir(ftp_path)
                ftp_path = os.path.join(ftp_path,os.path.basename(local_path))
    
            if not self._is_ftp_dir(ftp_path):
                self._mk_ftp_dir(ftp_path)
    
            os.chdir(local_path)
            local_files = os.listdir('.')
            for afile in local_files:
                if os.path.isdir(afile):
                    new_ftp_path = os.path.join(ftp_path,afile)
                    self.put_dir(afile,new_ftp_path,False)
                else:
                    self.put_file(afile,os.path.join(ftp_path,afile))
            os.chdir('..')
            return
        else:
            print 'ERROR:The dir:%s is not exist' %local_path
            return
    
    def close(self):
        self.sftp.close()
    
    def _is_ftp_dir(self,path):
        try:
            attr = self.sftp.lstat(path)
            attr = str(attr)
            if attr.startswith('d'):
                return True
            else:
                return False
        except:
            return False
    
    def _rm_ftp_dir(self,ftp_path):
        ftp_path = ftp_path.rstrip('/')
        if self._is_ftp_dir(ftp_path):
            self._cd_ftp_dir(ftp_path)
            ftp_files = self._get_ftp_filelst()
            for afile in ftp_files:
                if self._is_ftp_dir(afile):
                    self._rm_ftp_dir(afile)
                else:
                    #print 'sftp.remove:',afile
                    self.sftp.remove(afile)
            self._cd_ftp_dir('..')
            #print 'sftp.rmdir:',ftp_path
            self.sftp.rmdir(ftp_path)
            return
    
    def _rm_loc_dir(self,Dir):
        if os.path.isdir( Dir ):
            paths = os.listdir( Dir )
            for path in paths:
                filePath = os.path.join( Dir, path )
                if os.path.isfile( filePath ):
                    os.remove( filePath )
                elif os.path.isdir( filePath ):
                    self._rm_loc_dir(filePath)
    
    def _cd_ftp_dir(self,path):
        self.sftp.chdir(path)
    
    def _get_ftp_filelst(self):
        return self.sftp.listdir()
    
    def _mk_ftp_dir(self,path):
        self.sftp.mkdir(path)
    

    if name == '__main__':

    ser1 = FTPSync(serFr)
    ser1.login()
    ser1.get_dir(serFr['rdirname'],serFr['ldirname'])
    ser1.close()
    
    ser2 = FTPSync(serTo)
    ser2.login()
    ser2.put_dir(serTo['ldirname'],serTo['rdirname'])
    ser2.close()
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器