python网络自动运维

python自动化网络

使用telnet

# 引入telnetLib
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 = []
        # 判断是否有--more--
        while True:
            # 获取返回的结果
            command_result = self._tn.read_very_eager().decode('ascii')
            result_list.append(command_result)
            # 判断当前这一页是否有 'more'
            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:
                # 执行sql语句
                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()

查询

  # 查询mac
        serch = "select id from switch_list where mac like %s"

        cursor.execute(serch, [(result['mac_info'])])
        content = cursor.fetchone()
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值