如何通过Paramiko获取目录中所有SFTP文件的大小

Vic*_*ory 2 python sftp filesize paramiko

import paramiko
from socket import error as socket_error
import os 
server =['10.10.0.1','10.10.0.2']
path='/home/test/'
for hostname in server:
    try:
        ssh_remote =paramiko.SSHClient()
        ssh_remote.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        privatekeyfile = os.path.expanduser('~/.ssh/id')
        mykey = paramiko.RSAKey.from_private_key_file(privatekeyfile, password='test123')
        ssh_remote.connect(hostname, username = 'test1', pkey = mykey)
        sftp=ssh_remote.open_sftp()
        for i in sftp.listdir(path):
            info = sftp.stat(i)
            print info.st_size      
    except paramiko.SSHException as sshException:
        print "Unable to establish SSH connection:{0}".format(hostname)
    except socket_error as socket_err:
        print "Unable to connect connection refused"
Run Code Online (Sandbox Code Playgroud)

这是我的代码。我试图获取远程服务器文件的文件大小。但是下面的错误正在抛出。可以请一些指导吗?

错误

import paramiko
from socket import error as socket_error
import os 
server =['10.10.0.1','10.10.0.2']
path='/home/test/'
for hostname in server:
    try:
        ssh_remote =paramiko.SSHClient()
        ssh_remote.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        privatekeyfile = os.path.expanduser('~/.ssh/id')
        mykey = paramiko.RSAKey.from_private_key_file(privatekeyfile, password='test123')
        ssh_remote.connect(hostname, username = 'test1', pkey = mykey)
        sftp=ssh_remote.open_sftp()
        for i in sftp.listdir(path):
            info = sftp.stat(i)
            print info.st_size      
    except paramiko.SSHException as sshException:
        print "Unable to establish SSH connection:{0}".format(hostname)
    except socket_error as socket_err:
        print "Unable to connect connection refused"
Run Code Online (Sandbox Code Playgroud)

Mar*_*ryl 7

SFTPClient.listdir仅返回文件名,而不是完整路径。所以要在另一个 API 中使用文件名,你必须添加一个路径:

for i in sftp.listdir(path):
    info = sftp.stat(path + "/" + i)
    print info.st_size     
Run Code Online (Sandbox Code Playgroud)

虽然那是低效的。Paramiko 已经知道大小,您只是通过使用SFTPClient.listdir代替SFTPClient.listdir_attr(内部listdir调用listdir_attr)来丢弃信息。

for i in sftp.listdir_attr(path):
    print i.st_size  
Run Code Online (Sandbox Code Playgroud)