Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
666 views
in Technique[技术] by (71.8m points)

python - How to fetch sizes of all SFTP files in a directory through 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"

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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  

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...