环境
Python 3.6.8 (tags/v3.6.8:3c6b436a57, Dec 24 2018, 00:16:47) [MSC v.1916 64 bit (AMD64)] on win32
py文件保存时编码为utf-8
需求:
1、批量管理交换机、查看状态以及刷配置
2、设备主要为H3C和锐捷交换机,华为的类似
3、设备信息存储在excel表格中,执行结果返回到excel表格中
4、多进程,提高效率
import telnetlib
import time
from openpyxl import load_workbook
import os
from multiprocessing import Manager, Process, Pool
import multiprocessing
def tel(host, username, password,type):
print('启动telnet任务:IP地址(%s),进程ID(%s)...' % (host, os.getpid()))
try:
# 建立连接
tn = telnetlib.Telnet(host, port=23, timeout=5)
except Exception as n :
return (host+"Err0r:"+str(n))
if type=="华三":
tn.read_until(b":",timeout=2)
tn.write(username.encode(encoding="utf-8") + b"\n")
time.sleep(2)
tn.read_until(b"Password:",timeout=2)
tn.write(password.encode(encoding="utf-8") + b"\n")
time.sleep(2)
tn.write(b"dis clock \n")
time.sleep(2)
return tn.read_very_eager().decode(encoding="utf-8")
tn.write(b"quit\n")
time.sleep(1)
elif type=="锐捷":
tn.read_until(b"Username:",timeout=2)
tn.write(username.encode(encoding="utf-8") + b"\n")
time.sleep(2)
tn.read_until(b"Password:",timeout=2)
tn.write(password.encode(encoding="utf-8") + b"\n")
time.sleep(2)
tn.read_until(b">",timeout=2)
tn.write(b"enable \n")
tn.read_until(b"Password:",timeout=2)
tn.write(password.encode(encoding="utf-8") + b"\n")
time.sleep(2)
tn.write(b"show clock \n")
time.sleep(2)
return tn.read_very_eager().decode(encoding="utf-8")
tn.write(b"exit\n")
time.sleep(1)
class WS_out(object):
#结果对象
def __init__(self, ip, value):
self.ip = ip
self.value = value
def return_ip(self):
return self.ip
def return_value(self):
return self.value
if __name__ == "__main__":
username = "***"
password = "****"
file_home = './AC列表.xlsx'
wb = load_workbook(filename= file_home)
sheet_name='AC'
ws = wb[sheet_name]
rows=ws.max_row
print(rows)
cpus = multiprocessing.cpu_count()
#定义进程数量,设置为cpus核心的4倍
p = multiprocessing.Pool(cpus*4)
results=[]
for i in range(1,rows):
host=str(ws.cell(row = i+1, column = 2).value)
type=str(ws.cell(row = i+1, column = 6).value)
# print(host)
if host:
result =p.apply_async(tel, args=(host, username, password,type,))
results.append(WS_out(host,result))
print('Waiting for all subprocesses done...')
p.close()
p.join()
#结果写入excel表格
for result in results:
for i in range(1,rows):
if str(ws.cell(row = i+1, column = 2).value)==result.return_ip() :
out=result.return_value()
ws.cell(row = i+1, column = 7).value=out.get()
print(str(i)+"、主机IP:"+result.return_ip()+" 状态:成功ok" )
wb.save(file_home)
excel表格格式如下: