python自动化网络
使用telnet
from telnetlib import Telnet
import time
class ConnectSwitch:
_tn = ''
def __init__(self, host: str, username: str, password: str):
self.login_dict = {
'host': host,
'username': username,
'password': password,
}
def telnet_on(self):
"""执行命令"""
self._tn = Telnet(self.login_dict['host'], port=23, timeout=10)
self._tn.read_until(b"Username:")
self._tn.write(self.login_dict['username'].encode('ascii') + b'\n')
self._tn.read_until(b"Password")
self._tn.write(self.login_dict['password'].encode('ascii') + b'\n')
def telnet_command(self, command: str, et: int, st: int):
self._tn.write(command.encode('ascii') + b'\n')
time.sleep(et)
result_list = []
while True:
command_result = self._tn.read_very_eager().decode('ascii')
result_list.append(command_result)
if '---- More ----' in command_result.strip():
self._tn.write(b" ")
time.sleep(st)
else:
break
print("\n".join(result_list))
数组分割
def list_split(items, n):
return [items[i:i+n] for i in range(0, len(items), n)]
数据库
sql = "insert into switch_list(supplier,equipmentModel, mac, switchInterfaceOnline, switchInterfaceOffline,flow,created_at,updated_at)values (%s,%s,%s,%s,%s,%s,%s,%s)"
try:
cursor.executemany(sql, [(result['production_info'], result['model_info'], result['mac_info'],
result['interface_online'], result['interface_offline'],
result['total_flow'], time, time)])
self._db.commit()
except Exception as e:
print(e)
self._db.rollback()
查询
serch = "select id from switch_list where mac like %s"
cursor.execute(serch, [(result['mac_info'])])
content = cursor.fetchone()