paramiko--密钥连接远端服务器并递归目录
Posted 小陆同学
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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‘)
以上是关于paramiko--密钥连接远端服务器并递归目录的主要内容,如果未能解决你的问题,请参考以下文章