python使用paramiko模块通过ssh2协议对交换机进行配置的方法
该代码用的是paramiko模块,python版本是python2.7
下面上源码
#-*-coding:utf-8-*-
importparamiko
importtime
importos
port='22'
username='****'
password='****'
ip='****'#测试用的交换机ip
msg1flag=0
mycmd1flag=0
#核心方法,该方法连接远程主机并打开一个终端,并将该终端返回
defmsg1(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()
returnchan
exceptException,e:
mflag+=1
time.sleep(5)
ifmflag<3:
msg1(ip,mport,musername,mpassword,mflag)
#黄栋淋交换机开启审计专用
defmycmd(chan,my1flag):
try:
chan.send('system'+'\n')#输入命令
chan.send('****'+'\n')#输入命令
chan.send('****'+'\n')
chan.send('****'+'\n')
time.sleep(50)
i=1
whilei<3:
chan.send('\n')
i+=1
time.sleep(2)
result=chan.recv(65535)#得到命令返回的结果
printresult
strlen=len(result)#得到结果字符串的长度
printstrlen
returnresult
exceptException,e:
#printe
my1flag+=1
time.sleep(5)
ifmy1flag<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协议对交换机进行配置的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。