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

yipeiwu_com6年前Python基础

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

下面上源码

# -*- coding: utf-8 -*-

import paramiko
import time
import os

port = '22'
username = '****'
password = '****'
ip = '****'  # 测试用的交换机ip

msg1flag = 0
mycmd1flag = 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协议对交换机进行配置的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python获取当前计算机cpu数量的方法

本文实例讲述了python获取当前计算机cpu数量的方法。分享给大家供大家参考。具体分析如下: 这里实际上返回的是计算机的cpu核心数,比如cpu是双核的,则返回2,如果双四核cpu,则...

python jieba分词并统计词频后输出结果到Excel和txt文档方法

python jieba分词并统计词频后输出结果到Excel和txt文档方法

前两天,班上同学写论文,需要将很多篇论文题目按照中文的习惯分词并统计每个词出现的频率。 让我帮她实现这个功能,我在网上查了之后发现jieba这个库还挺不错的。 运行环境: 安装...

Python编写登陆接口的方法

Python编写登陆接口的方法

本文实例为大家分享了Python编写登陆接口的具体代码,供大家参考,具体内容如下 1.输入用户名密码; 2.认证成功后显示欢迎信息; 3.错误三次后,账号被锁定。  账号文件:...

python 列表中[ ]中冒号‘:’的作用

中括号[ ]:用于定义列表或引用列表、数组、字符串及元组中元素位置 list1 = ['physics', 'chemistry', 1997, 2000] list2 = [1,...

python使用matplotlib库生成随机漫步图

python使用matplotlib库生成随机漫步图

本教程使用python来生成随机漫步数据,再使用matplotlib将数据呈现出来 开发环境 操作系统: Windows10 IDE: Pycharm 2017.1.3 Python...