简体   繁体   中英

SSH Dependant session - Python Paramiko

Wondering if anyone has done it, or am I to descover the hot water here. The below script is my base for executing commands ( for now on one device cause I don`t know how to pass multiple ), but I need to make it a dependant session. Essentially I have a jump host through which the SSH to my end device should occur. SSH to jump host, and from it SSH to end device(s). Ideas?

#Importing modules
import paramiko
import sys
import time

#setting parameters like host IP, username, passwd and number of iterations to gather cmds
HOST = "1.1.1.1"
USER = "admin"
PASS = "passwd"
ITERATION = 3

#A function that logins and execute commands
def fn():
  client1=paramiko.SSHClient()
  #Add missing client key
  client1.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  #connect to switch
  client1.connect(HOST,username=USER,password=PASS)
  print "SSH connection to %s established" %HOST
  #Gather commands and read the output from stdout
  stdin, stdout, stderr = client1.exec_command('show version\n')
  print stdout.read()
  stdin, stdout, stderr = client1.exec_command('show alarms | no-more\n')
  print stdout.read()
  stdin, stdout, stderr = client1.exec_command( 'show processes memory | no-more\n')
  print stdout.read()
  client1.close()
  print "Logged out of device %s" %HOST

#for loop to call above fn x times. Here x is set to 3
for x in xrange(ITERATION):
  fn()
  print "%s Iteration/s completed" %(x+1)
  print "********"
  time.sleep(5) #sleep for 5 seconds

You could use direct-tcpip channel to create a "socket", which you could then give to paramiko.SSHClient :

proxy = client1.get_transport().open_channel('direct-tcpip',
                                             dest_addr=(dest_ip, dest_port),
                                             src_addr=('localhost', 0))
client2 = paramiko.SSHClient()
client2.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client2.connect(username='user', password='pass', sock=proxy)

See paramiko.Transport.open_channel docs .

For that to work though, the server that the client1 is connected to must allow opening of that kind of a channel. Most do, but in OpenSSH you can have it disabled for "security reasons" (which has been shown time and time again to provide no additional security at all, but it's possible).

In case your server has this option disabled, you could use any jumphost's process, that has an ability to talk to the target server via TCP, eg Netcat. See my self-answered question for the code of that .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM