小陆同学

python 中文名:蟒蛇,设计者:Guido van Rossum

导航

paramiko--密钥连接远端服务器并递归目录

from stat import S_ISDIR as isdir
try:
    private_key = paramiko.RSAKey.from_private_key_file('/root/.ssh/id_rsa')
    t = paramiko.Transport((ip, 22))
    t.connect(username='root', pkey=private_key)
    sftp = paramiko.SFTPClient.from_transport(t)
    remote_file = sftp.stat(dir)
    response = []
    if isdir(remote_file.st_mode):
        try:
            for i in sftp.listdir(dir):
                res = {}
                next_path = os.path.join(dir,i)
                if isdir(sftp.stat(next_path).st_mode):

                    res = self.getPathDetail(ip,next_path,root_path)
                    response.extend(res)
                else:

                    res['pId'] = dir
                    res['id'] = next_path
                    res['name'] = next_path.split(root_path)[-1]
                    response.append(res)
            else:
                res = {}
                res['name'] = os.path.basename(dir)
                res['pId'] = dir
                res['id'] = dir
                response.append(res)

        except:
                pass
    # print(response)
    sftp.close()
    t.close()
    return response
except:
    return []  # paramiko连接失败,可能是没有配置密钥

 

 

lse:
            print(sp + "普通文件:", fileName)
# getAllDirRE("/mnt")
paramiko递归远程目录
import paramiko,os
from stat import S_ISDIR as isdir

def conn():
        t = paramiko.Transport(('192.168.1.XX', 22))
        t.connect(username='root', password='123456')
        sftp = paramiko.SFTPClient.from_transport(t)
        return sftp
def recursion(dir):
        sftp = conn()
        remote_file = sftp.stat(dir)
        if isdir(remote_file.st_mode):
                try:
                        for i in sftp.listdir(dir):
                                next_path = os.path.join(dir,i)
                                if isdir(sftp.stat(next_path).st_mode):
                                        recursion(next_path)
                                else:
                                        print(next_path)
                        else:
                                print(dir)
                except:
                        pass
        else:
                print(dir)
#
# if __name__ == '__main__':
#         recursion('/data')

 

posted on 2020-04-17 23:13  小陆同学  阅读(443)  评论(0编辑  收藏  举报