@contextmanager
def mongo_connection():
server = SSHTunnelForwarder(
'192.168.20.10',
ssh_username='username',
ssh_password='password',
remote_bind_address=('127.0.0.1', 27017))
server.start()
yield server
server.stop()
with mongo_connection() as server:
client = MongoClient('127.0.0.1', server.local_bind_port)
...