import sys
import py

#from traceback import format_tb

def readdir(host, dir):
    
    codestring = """
    import os
    channel.send(os.listdir(%r))
    """ % dir
    
    targethost = py.execnet.SshGateway(host)
    channel = targethost.remote_exec(codestring)

    try:
        contents = channel.receive()
    except:
        type, value, traceback = sys.exc_info()
        print "type: %s \n\nvalue: %s\n\ntrace: %s\n" % (type, value, traceback)
        lines = repr(value).split('\n')
        contents = []
        for x in lines:
            if x.startswith('OSError'):
                contents.append(x)
    finally:
        channel.waitclose(10.0)
        channel.close()        
        targethost.exit()
    
    return contents

contents = readdir('localhost', '/some/where')

if not contents[0].startswith('OSError'):
    print contents
else:
    print contents
    raise Exception('There was a FileSystem access problem')
