How do you SSH through a bastion host from Python?
AdvancedConceptKubernetes, Docker & SSH clients
Answer
With Fabric, pass a gateway Connection:
bastion = Connection("bastion.acme.com", user="ops")
c = Connection("10.0.2.20", user="ec2-user", gateway=bastion)
c.run("hostname")
With paramiko, open a direct-tcpip channel on the bastion's transport and pass it as sock= when connecting to the target. On AWS, many teams avoid bastions entirely with SSM Session Manager (aws ssm start-session, or ssm.send_command from boto3 for remote command execution without any inbound SSH).
More on Kubernetes, Docker & SSH clients
How does the official Kubernetes Python client authenticate?BeginnerHow do you list pods with high restart counts using the Python client?BeginnerHow do you patch or scale a Deployment with the Python client?IntermediateHow does `watch.Watch()` work, and what is a `410 Gone`?AdvancedHow do you apply a YAML manifest from Python?AdvancedHow do you use the Docker SDK for Python?Beginner