該代碼用的是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協議對交換機進行配置的方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061
					微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
					
