You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flask无法推送交换机接口Last Input数据至HTML表格排查

问题

尝试获取交换机接口的Last Input时间,通过Flask推送至HTML页面的表格中,已成功获取数据列表,但HTML无法正常展示。

原Flask代码

def index():
    logging.basicConfig(filename='netmiko.log', level=logging.DEBUG)
    device = {
    'device_type':'cisco_ios_telnet',
    'ip': '10.10.20.250',
    'username': 'admin',
    'password': 'cisco',
    'port':23,
    }

    with ConnectHandler(**device) as net_connect:
    # Enter enable mode
        net_connect.enable()

    # Send "show interfaces" command and get output
        show_output = net_connect.send_command('show interfaces')

    net_connect.disconnect()

    interfaces_list = []
    for line in show_output.splitlines():
        if line.startswith('Gigabit'):
        # extract the interface name
            interface_name = line.split()[0]
        # extract the last input time
            if line.startswith('  Last input '):
            last_input_time = line.split('  Last input ')[1].split(',')[0]
        interfaces_list.append(f"{interface_name} - Last input {last_input_time}")
        else:
            continue    
        
    return render_template('index.html', interfaces=interfaces_list)

if __name__ == '__main__':
    app.run(debug=True)  

原HTML代码(templates/index.html)

<!DOCTYPE html>
<html>
<head>
    <title>Show Interfaces</title>
</head>
<body>
    <table>
        <thead>
            <tr>
                <th>Interface</th>
                <th>Last Input</th>
            </tr>
        </thead>
        <tbody>
            {% for interface in interfaces %}
            <tr>
                <td>{{ interface.interface }}</td>
                <td>{{ interface.last_input }}</td>
            </tr>
            {% endfor %}
        </tbody>
    </table>
</body>
</html>

Cisco设备show interfaces输出示例

GigabitEthernet3/0 is up, line protocol is up (connected)
 Hardware is iGbE, address is 0c82.6bf0.000c (bia 0c82.6bf0.000c)
 Description: VPC
 MTU 1500 bytes, BW 1000000 Kbit/sec, DLY 10 usec,
    reliability 255/255, txload 1/255, rxload 1/255
 Encapsulation ARPA, loopback not set
 Keepalive set (10 sec)
 Auto Duplex, Auto Speed, link type is auto, media type is RJ45
 output flow-control is unsupported, input flow-control is unsupported
 ARP type: ARPA, ARP Timeout 04:00:00
 Last input 00:21:33, output 00:00:01, output hang never
 Last clearing of "show interface" counters never
 Input queue: 0/75/0/0 (size/max/drops/flushes); Total output drops: 0
 Queueing strategy: fifo
 Output queue: 0/0 (size/max)
 5 minute input rate 0 bits/sec, 0 packets/sec
 5 minute output rate 0 bits/sec, 0 packets/sec
    7 packets input, 1816 bytes, 0 no buffer
    Received 6 broadcasts (6 multicasts)
    0 runts, 0 giants, 0 throttles
    0 input errors, 0 CRC, 0 frame, 0 overrun, 0 ignored
    0 watchdog, 6 multicast, 0 pause input
    749 packets output, 60803 bytes, 0 underruns
    0 output errors, 0 collisions, 2 interface resets
    0 unknown protocol drops
    0 babbles, 0 late collision, 0 deferred
    0 lost carrier, 0 no carrier, 0 pause output
    0 output buffer failures, 0 output buffers swapped out
 GigabitEthernet3/1 is up, line protocol is up (connected)
 Hardware is iGbE, address is 0c82.6bf0.000d (bia 0c82.6bf0.000d)
 Description: VPC
 MTU 1500 bytes, BW 1000000 Kbit/sec, DLY 10 usec,

错误分析及解决方案

1. 数据结构不匹配

你的Flask代码中,interfaces_list存储的是字符串(比如"GigabitEthernet3/0 - Last input 00:21:33"),但HTML模板期望的是包含interface和last_input字段的字典/对象。模板里的{{ interface.interface }}和{{ interface.last_input }}无法从字符串中提取属性,导致展示为空或报错。

2. 数据提取逻辑错误

原代码的循环逻辑有两个问题:

  • 缩进错误:判断line.startswith(' Last input ')的代码块缩进错误,会导致它只在line.startswith('Gigabit')的条件下执行,但Last input行和接口名行是分开的,不会在同一个迭代中触发。
  • 变量未定义风险:当还没读取到Last input行时,last_input_time未定义就被加入列表,会引发NameError。

修正后的代码

修正后的Flask代码

def index():
    logging.basicConfig(filename='netmiko.log', level=logging.DEBUG)
    device = {
        'device_type':'cisco_ios_telnet',
        'ip': '10.10.20.250',
        'username': 'admin',
        'password': 'cisco',
        'port':23,
    }

    with ConnectHandler(**device) as net_connect:
        net_connect.enable()
        show_output = net_connect.send_command('show interfaces')

    interfaces_list = []
    current_interface = None

    for line in show_output.splitlines():
        # 识别接口名行,记录当前接口
        if line.startswith('Gigabit'):
            current_interface = line.split()[0]
        # 识别Last input行,提取时间并组装字典
        elif line.strip().startswith('Last input'):
            if current_interface:
                last_input_time = line.split('Last input ')[1].split(',')[0].strip()
                interfaces_list.append({
                    'interface': current_interface,
                    'last_input': last_input_time
                })
                # 重置当前接口,避免重复匹配
                current_interface = None

    return render_template('index.html', interfaces=interfaces_list)

if __name__ == '__main__':
    app.run(debug=True)

修正后的HTML代码

<!DOCTYPE html>
<html>
<head>
    <title>Show Interfaces</title>
    <style>
        table { border-collapse: collapse; margin: 20px; }
        th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
        th { background-color: #f2f2f2; }
    </style>
</head>
<body>
    <table>
        <thead>
            <tr>
                <th>Interface</th>
                <th>Last Input</th>
            </tr>
        </thead>
        <tbody>
            {% for interface in interfaces %}
            <tr>
                <td>{{ interface.interface }}</td>
                <td>{{ interface.last_input }}</td>
            </tr>
            {% endfor %}
        </tbody>
    </table>
</body>
</html>

内容的提问来源于stack exchange,提问作者karoks

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 23:44:56