首页 > 编程 > Python > 正文

python使用paramiko模块通过ssh2协议对交换机进行配置的方法

2019-11-25 12:14:03
字体:
来源:转载
供稿:网友

该代码用的是paramiko模块,python版本是python2.7

下面上源码

# -*- coding: utf-8 -*-import paramikoimport timeimport osport = '22'username = '****'password = '****'ip = '****'  # 测试用的交换机ipmsg1flag = 0mycmd1flag = 0# 核心方法,该方法连接远程主机并打开一个终端,并将该终端返回def msg1(ip,mport,musername,mpassword,mflag):  try:    # 设置ssh连接的远程主机地址和端口    t = paramiko.Transport(ip, mport)    # 设置登录名和密码    t.connect(username=musername, password=mpassword)    # 连接成功后打开一个channel    chan = t.open_session()    # 设置会话超时时间    chan.settimeout(timeout=180)    # 打开远程的terminal    chan.get_pty()    # 激活terminal    chan.invoke_shell()    return chan  except Exception,e:    mflag += 1    time.sleep(5)    if mflag < 3:      msg1(ip,mport,musername,mpassword,mflag)# 黄栋淋交换机开启审计专用def mycmd(chan,my1flag):  try:    chan.send('system' + '/n') # 输入命令    chan.send('****' + '/n')  # 输入命令    chan.send('****' + '/n')    chan.send('****' + '/n')    time.sleep(50)    i = 1    while i < 3:      chan.send('/n')      i += 1    time.sleep(2)    result = chan.recv(65535)   # 得到命令返回的结果    print result    strlen = len(result)      # 得到结果字符串的长度    print strlen    return result  except Exception,e:    # print e    my1flag += 1    time.sleep(5)    if my1flag < 3:      mycmd(chan,my1flag)nowtime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) # 时间# 测试项chan_ip_test = msg1(ip,port,username,password,msg1flag)resu_ip_test = mycmd(chan_ip_test,mycmd1flag)

以上这篇python使用paramiko模块通过ssh2协议对交换机进行配置的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持武林网。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表