robey/paramiko — Issue #53: SFTP File Handler doesn't raise Exceptions if the SSH Client or SFTP session are out of scope
Author: victorhooi
Created: 2011-11-15 06:13:57+00:00
State: open

Hi,

I had some Python code with two functions, let's call them alice() and bob().

alice() would call bob(), and bob() would open up a SSH session, and return a SFTP file handler to alice().

```
#!/usr/bin/env python2
import paramiko

def get_instances_cfg():
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect('some_server', username='victorhooi')
sftp = client.open_sftp()
file = sftp.file('/tmp/instances.cfg')

# This would print out the file fine.
# for row in file:
# print(row)

return file
#sftp.close()
#client.close()

def get_root_directory():
instances_cfg = get_instances_cfg()

# The following would print out nothing.
for row in instances_cfg:
print(row)

if __name__ == '__main__':
get_root_directory()
```

I could iterate over the file handler fine in bob(), however in alice() it seemed to silently fail, printing nothing.

Anyhow, somebody pointed out to me that it was probably a scoping issue - when I left bob(), client and sftp would go out of scope, even though I returned file.

I made client, sftp and sftp global, and this then worked fine - I could iterate over file in alice().

My question is - I assume this is by design, right? The SFTP file handler won't work if the client doesn't exist in your current scope?

Should there be some kind of error message or exception raised if you try to access a SFTP file handler that doesn't have the original SSHClient or SFTP session around?

In my case, it seemed to be a valid SFTP file handler, but it just didn't contain any rows.

Cheers,
Victor