SSH依赖会话-Python Paramiko

时间:2019-11-20 17:43:43

标签: python ssh paramiko

想知道是否有人这样做了,还是我在这里发现热水。下面的脚本是我执行命令的基础(目前在一个设备上,因为我不知道如何传递多个脚本),但是我需要使它成为一个依赖的会话。本质上,我有一个跳转主机,通过该主机可以对我的终端设备进行SSH。 SSH跳转到主机,然后从SSH跳转到终端设备。想法?

#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

1 个答案:

答案 0 :(得分:0)

您可以使用direct-tcpip频道创建一个“套接字”,然后将其分配给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

为使此功能正常运行,client1连接到的服务器必须允许打开这种通道。大多数都可以,但是在OpenSSH中,您可以出于“安全原因”将其禁用(已经多次显示,它根本不提供额外的安全性,但是有可能)。

如果您的服务器禁用了此选项,则可以使用任何Jumphost的进程,该进程具有通过TCP与目标服务器进行通信的能力,例如网猫。 See my self-answered question for the code of that