How to do multihop ssh with fabric

2024/9/16 18:18:25

I have a nat and it has various server So from my local server I want to go to nat and then from nat i have to ssh to other machines

Local-->NAT(abcuser@publicIP with key 1)-->server1(xyzuser@localIP with key 2) nat has different ssh key and each of the server has different ssh key how can i accomplish this type of multihop ssh using fabric I tried using env.roledefs feature but it doesnt seems to be working also I am not sure how to define two ssh keys.I know we can define a list of keys with env.key_filename but issue is will it check each key with each server?How can I be more specific and match a key with one server only

I have tried using command from my local machine fab deploy -g '[email protected]' -i '/home/aman/Downloads/aws_oms.pem' and my script is

from __future__ import with_statement
from fabric.api import local, run, cd, env, execute
env.hosts=['[email protected]']
env.key_filename=['/home/ec2-user/varnish_cache.pem']
def deploy():run("uname -a")
Answer

It's possible. Double hop to 10.0.0.2 (and list files) via gateway hop 10.0.0.1. Basically, you simply nest the connections with the gateway parameter.

# coding: utf-8from fabric import Connectionpath = '/'
conn1 = Connection(host='[email protected]', connect_kwargs={'password': '***'})
conn2 = Connection(host='[email protected]', connect_kwargs={'password': '***'}, gateway=conn1)
result = conn2.run(f'''cd {path} && ls -al''', hide=True)
conn2.close()
conn1.close()
msg = "Ran {0.command!r} on {0.connection.host}, got stdout:\n{0.stdout}"
print(msg.format(result))

Please remember to run the SSH connection manually once to introduce the servers to each other!

Install via

pip3 install --upgrade fabric
pip3 install cryptography==2.4.2  # optional to hide some annoying warnings

http://docs.fabfile.org/en/latest/concepts/networking.html

Python 3.6+.

https://en.xdnf.cn/q/72869.html

Related Q&A

Python - Converting CSV to Objects - Code Design

I have a small script were using to read in a CSV file containing employees, and perform some basic manipulations on that data.We read in the data (import_gd_dump), and create an Employees object, cont…

Python multithreading - memory not released when ran using While statement

I built a scraper (worker) launched XX times through multithreading (via Jupyter Notebook, python 2.7, anaconda). Script is of the following format, as described on python.org:def worker():while True:i…

Delete files that are older than 7 days

I have seen some posts to delete all the files (not folders) in a specific folder, but I simply dont understand them.I need to use a UNC path and delete all the files that are older than 7 days.Mypath …

Doctests: How to suppress/ignore output?

The doctest of the following (nonsense) Python module fails:""" >>> L = [] >>> if True: ... append_to(L) # XXX >>> L [1] """def append_to(L):…

Matplotlib not showing xlabel in top two subplots

I have a function that Ive written to show a few graphs here:def plot_price_series(df, ts1, ts2):# price series line graphfig = plt.figure()ax1 = fig.add_subplot(221)ax1.plot(df.index, df[ts1], label=t…

SQLAlchemy NOT exists on subselect?

Im trying to replicate this raw sql into proper sqlalchemy implementation but after a lot of tries I cant find a proper way to do it:SELECT * FROM images i WHERE NOT EXISTS (SELECT image_idFROM events …

What is the correct way to obtain explanations for predictions using Shap?

Im new to using shap, so Im still trying to get my head around it. Basically, I have a simple sklearn.ensemble.RandomForestClassifier fit using model.fit(X_train,y_train), and so on. After training, Id…

value error when using numpy.savetxt

I want to save each numpy array (A,B, and C) as column in a text file, delimited by space:import numpy as npA = np.array([5,7,8912,44])B = np.array([5.7,7.45,8912.43,44.99])C = np.array([15.7,17.45,189…

How do I retrieve key from value in django choices field?

The sample code is below:REFUND_STATUS = ((S, SUCCESS),(F, FAIL) ) refund_status = models.CharField(max_length=3, choices=REFUND_STATUS)I know in the model I can retrieve the SUCCESS with method get_re…

Errno13, Permission denied when trying to read file

I have created a small python script. With that I am trying to read a txt file but my access is denied resolving to an no.13 error, here is my code:import time import osdestPath = C:\Users\PC\Desktop\N…