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"
这是我的代码。我试图获取远程服务器文件的文件大小。但是下面的错误就是投掷。有人可以指导一下吗?
错误
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
SFTPClient.listdir
仅返回文件名,而不是完整路径。因此,要在另一个API中使用文件名,您必须添加一个路径:
for i in sftp.listdir(path):
info = sftp.stat(path + "/" + i)
print info.st_size
虽然那效率很低。 Paramiko已经知道了这个尺寸,你只是通过使用SFTPClient.listdir
而不是SFTPClient.listdir_attr
(listdir
在内部调用listdir_attr
)来抛弃信息。
for i in sftp.listdir_attr(path):
print i.st_size