How to fetch sizes of all SFTP files in a directory through Paramiko

橙三吉。 提交于 2019-12-01 09:07:12

问题


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"

This is my code. I tried to get file size of remote server files. But below error was throwing. Can some please guide on this?

Error

Traceback (most recent call last):
  File "<stdin>", line 15, in <module>
  File "/usr/lib/python2.6/site-packages/paramiko/sftp_client.py", line 337, in stat
    t, msg = self._request(CMD_STAT, path)
  File "/usr/lib/python2.6/site-packages/paramiko/sftp_client.py", line 624, in _request
    return self._read_response(num)
  File "/usr/lib/python2.6/site-packages/paramiko/sftp_client.py", line 671, in _read_response
    self._convert_status(msg)
  File "/usr/lib/python2.6/site-packages/paramiko/sftp_client.py", line 697, in _convert_status
    raise IOError(errno.ENOENT, text)
IOError: [Errno 2] No such file

回答1:


SFTPClient.listdir returns file names only, not a full path. So to use the filename in another API, you have to add a path:

for i in sftp.listdir(path):
    info = sftp.stat(path + "/" + i)
    print info.st_size     

Though that's inefficient. Paramiko knows the size already, you are just throwing the information away by using SFTPClient.listdir instead of SFTPClient.listdir_attr (listdir calls listdir_attr internally).

for i in sftp.listdir_attr(path):
    print i.st_size  


来源:https://stackoverflow.com/questions/51298467/how-to-fetch-sizes-of-all-sftp-files-in-a-directory-through-paramiko

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!