网络编程
位置:首页>> 网络编程>> Python编程>> python使用paramiko模块通过ssh2协议对交换机进行配置的方法

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

作者:一路湘北  发布时间:2022-05-16 03:03:17 

标签:python,paramiko,ssh2,交换机

该代码用的是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)

来源:https://blog.csdn.net/qq_25134989/article/details/78918188

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com