码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2020-04-17 23:56:53      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:res   密钥   end   rsa   pass   tail   服务   sel   port   

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‘)

 

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

标签:res   密钥   end   rsa   pass   tail   服务   sel   port   

原文地址:https://www.cnblogs.com/lutt/p/12723292.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!