1

我目前编写的这个脚本运行良好,但有一个限制,我无法确定哪个源 IP 可以打开服务器的 SSH。对于具有多个接口的路由器,这将非常有用。我读过sock或者channel可以使用,但我不知道如何实现它们,也找不到示例。

谢谢!

from junos import Junos_Context
import paramiko
from datetime import datetime
import jcs

user = Junos_Context['user-context']['login-name']
hostname = Junos_Context['hostname']
now = datetime.now()
day = now.strftime('%Y%m%d')
hour = now.strftime('%H%M%S')

#Sets up the ssh session and logs in as login "simone" with password "simone"
#to host '192.168.2.2' 

host = '192.168.2.2'
login = 'simone'
passw = 'simone'

try:
   ssh = paramiko.SSHClient()
   ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
   ssh.connect(host, username=login, password=passw, look_for_keys=False, allow_agent=False)
  chan = ssh.invoke_shell()
except:
   print "Login to %s failed" % (host,)
   chan = False

if chan:
   sftp = ssh.open_sftp()
   sftp.put('/config/juniper.conf.gz',
  '/simone/backups/%s_%s_%s_%s_juniper.conf.gz' % (user,hostname,day,hour))

   sftp.close()
   ssh.close()

   print "All it's OK %s ! " % (user,)

else:
   print "Sorry, there is no connection to the host %s" % (host,)
4

2 回答 2

3

使用sock参数 ofSSHClient.connect提供绑定到您选择的源地址的自定义套接字。基于Python 在打开套接字时可以选择什么网络适配器?,这应该这样做:

import socket
s = socks.socket()
s.bind((local_address, 0))
s.connect((host, 22))
ssh.connect(
    host, username=login, password=passw, look_for_keys=False, allow_agent=False, sock=s)
于 2020-06-26T16:05:47.363 回答
-2

好的,现在可以了!非常感谢!我的脚本最终是:

sok = socket.socket()
sok.bind((local_address, 0))
sok.connect((host, 22))

ssh.connect(host, username=login, password=passw, look_for_keys=False, allow_agent=False, sock=sok)
于 2020-06-27T15:56:56.667 回答