python uses paramiko module to configure switch through ssh2 protocol
- 2021-07-26 08:22:28
- OfStack
This code uses the paramiko module, and the python version is python 2.7
The source code below
# -*- coding: utf-8 -*-
import paramiko
import time
import os
port = '22'
username = '****'
password = '****'
ip = '****' # Switch for test ip
msg1flag = 0
mycmd1flag = 0
# Core method that connects to the remote host and opens the 1 Terminal, and returns the terminal
def msg1(ip,mport,musername,mpassword,mflag):
try:
# Settings ssh Connected remote host address and port
t = paramiko.Transport(ip, mport)
# Set the login name and password
t.connect(username=musername, password=mpassword)
# Open after successful connection 1 A channel
chan = t.open_session()
# Set the session timeout
chan.settimeout(timeout=180)
# Open the remote terminal
chan.get_pty()
# Activate terminal
chan.invoke_shell()
return chan
except Exception,e:
mflag += 1
time.sleep(5)
if mflag < 3:
msg1(ip,mport,musername,mpassword,mflag)
# Huang Donglin Switch Opens Special Audit
def mycmd(chan,my1flag):
try:
chan.send('system' + '\n') # Input command
chan.send('****' + '\n') # Input command
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) # Get the result returned by the command
print result
strlen = len(result) # Get the length of the resulting string
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())) # Time
# Test item
chan_ip_test = msg1(ip,port,username,password,msg1flag)
resu_ip_test = mycmd(chan_ip_test,mycmd1flag)