I’m attempting to use Paramiko (Python SSH library) to read a remote file, and iterate through the lines.
My file looks something like this:
# Instance Name VERSION COMMENT
Bob 1.5 Bob the Builder
Sam 1.7 Play it again, Sam
My Paramiko code looks something like this:
def get_instances_cfg(self):
'''
Gets a file handler to the remote instances.cfg file.
'''
transport = paramiko.Transport(('10.180.10.104', 22))
client = paramiko.SSHClient()
#client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect('some_host', username='victorhooi', password='password')
sftp = client.open_sftp()
fileObject = sftp.file('/tmp/instances.cfg','r')
return fileObject
def get_root_directory(self):
'''
Reads the global instances.cfg file, and returns the instance directory.
'''
self.logger.info('Getting root directory')
instances_cfg = self.get_instances_cfg()
first_line = instances_cfg.next() # We skip the header row.
instances = {}
for row in instances_cfg:
name, version, comment = row.split(None, 2)
aeg_instances[name] = {
'version': version,
'comment': comment,
}
For some reason, when I run the above, I get a StopIteration error when I run .next() on the SFTP file handler:
first_line = instances_cfg.next() # We skip the header row.
File "/home/hooivic/python2/lib/python2.7/site-packages/paramiko/file.py", line 108, in next
raise StopIteration
StopIteration
This is strange, because the instances textfile I’m reading has three lines in it – I’m using .next() to skip the header line.
When I open the file locally, using Python’s open(), .next() works fine.
Also, I can iterate through the SFTP file handler fine, and it will print all three lines.
And using .readline() instead of .next() seems to work fine as well – not sure why the .next() isn’t playing nice.
Is this some quirk of Paramiko’s SFTP file handler, or am I missing something in the code above?
Cheers,
Victor
The the
next()function is simply callingreadline()internally. The only thing that can cause aStopIterationis if readline returned an empty string (look at the code, it’s 4 lines).Look at what the return of
readline()is for your file. If it’s returning an empty string, there has to be a bug in the line-buffering algorithm used by paramiko.