使用特定 IP 源的 Python Paramiko SSH 脚本 [英] Python Paramiko SSH script that use specific IP source

查看:50
本文介绍了使用特定 IP 源的 Python Paramiko SSH 脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

谢谢!

from junos import Junos_Context进口paramiko从日期时间导入日期时间进口jcsuser = Junos_Context['user-context']['login-name']主机名 = Junos_Context['主机名']现在 = datetime.now()day = now.strftime('%Y%m%d')小时 = now.strftime('%H%M%S')#设置ssh会话并以登录名simone"登录;密码为simone"#托管'192.168.2.2'主机 = '192.168.2.2'登录 = '西蒙尼'passw = '西蒙尼'尝试: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)陈 = ssh.invoke_shell()除了:打印登录 %s 失败";% (主持人,)陈=假如果陈:sftp = ssh.open_sftp()sftp.put('/config/juniper.conf.gz','/simone/backups/%s_%s_%s_%s_juniper.conf.gz'%(用户,主机名,天,小时))sftp.close()ssh.close()打印一切都好%s!"%(用户,)别的:打印抱歉,没有与主机 %s 的连接";% (主持人,)

解决方案

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

<块引用>

sok = socket.socket()sok.bind((local_address, 0))sok.connect((主机,22))ssh.connect(host, username=login, password=passw, look_for_keys=False, allow_agent=False, sock=sok)

I have currently written this script which works fine, but has a limitation, I can't decide which source IP can open SSH with the server. For routers with multiple interfaces it would be extremely useful. I read that sock or channel could be used, but I don't know how to implement them and I can't find examples.

Thanks!

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,)

解决方案

Ok, now it works! Many thanks! My script finaly is:

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)

这篇关于使用特定 IP 源的 Python Paramiko SSH 脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆