The code below (main.py) realizes the access to a host through SSH and creates a tunnel for the IP to be accessed by 127.0.0.1:
import paramiko
from sshtunnel import SSHTunnelForwarder
from paramiko import SSHClient
class SSH:
def __init__(self):
self.ssh = SSHClient()
self.ssh.load_system_host_keys()
self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.ssh.connect(hostname='127.0.0.1',port='10022',username='root',password='root')
def exec_cmd(self,cmd):
stdin,stdout,stderr = self.ssh.exec_command(cmd)
if stderr.channel.recv_exit_status() != 0:
print (stderr.read())
else:
print (stdout.read())
server = SSHTunnelForwarder(
'192.168.100.10',
ssh_username="root",
ssh_password="root",
remote_bind_address=('127.0.0.1', 22),
local_bind_address=('0.0.0.0', 10022)
)
server.start()
if __name__ == '__main__':
ssh = SSH()
stdin,stdout,stderr = ssh.ssh.exec_command("hostname")
retorno = stdout.read()
print (retorno)
server.stop()
I'm trying to access a specific machine and for that, I have to access a machine initially for network reasons.
In Python, I run main.py to perform SSH on the initial machine and after that I create a tunnel for the other machine, managing to execute remote commands on it.
----------------------------------------------------------------------
|
-------------+ | +----------+ +---------+
HOST | | | HOST | | HOST |
MAIN.PY | -- SSH ----> | | INITIAL | -- TUNNEL --> | WANTED |
-------------+ | +----------+ +---------+
|
----------------------------------------------------------------------
The topology accessing by Putty is: Access initial connection (the one you have network rules created for) and then execute the SSH command for the other machine, arriving at the desired machine.
As stated in the code above, I can only access the first host. Can anybody help me?