juliet070
2015-06-12 08:29
采纳率: 100%
浏览 2.0k

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()
    
    点赞 打赏 评论
  • juliet070 2015-06-12 08:47

    #!/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()
    
    点赞 打赏 评论
  • juliet070 2015-06-12 08:49

    -* - coding: UTF-8 -* -

    import gl

    def fun():

    print gl._a

    print gl._b

    fun()

    print "-----------for-----------"

    for i in range(0,5):

    print i;
    continue
    print "2233"

    break

    else:
    print i

    print "-----------while-----------"

    while True:
    print i
    break
    else:
    print "a"

    print "-----------def1-----------"

    def sumOf(a, b):
    return a + b

    print sumOf(3,4)

    print "-----------def2-----------"

    def func():
    global x
    print "x is ", x
    x = 1

    x = 3
    func()
    print x

    print "-----------def3-----------"

    def say(msg, times = 1):
    print msg * times

    say("peter")
    say("peter", 3)

    print "-----------def4-----------"

    print "-----------def5-----------"

    def func():
    '''This is self-defined function
    这是自定义函数

    Do nothing
    什么都不做'''
    pass

    print func.__doc__

    点赞 打赏 评论

相关推荐 更多相似问题