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

Django网页按钮触发解析RAW输出并展示指定组播IP

Solution to Extract and Display Multicast IPs from SSH Output

Let's get this sorted out for you. Here's the revised view.py code that handles decoding the SSH output, extracts the multicast IPs, formats them as requested, and cleans up the SSH session properly:

import paramiko
import time
import re
from django.shortcuts import render

def your_view_function(request):
    if 'RETRIEVE' in request.POST:
        remote_conn_pre = paramiko.SSHClient()
        remote_conn_pre.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        try:
            remote_conn_pre.connect(hostname='172.31.255.4', port=22, username='admin', password='******', look_for_keys=False, allow_agent=False)
            remote_conn = remote_conn_pre.invoke_shell()
            
            # Send commands to the device
            remote_conn.send("\n")
            remote_conn.send("terminal length 0\n")
            remote_conn.send("sh mvr members\n")
            time.sleep(1)  # Give time for the device to respond
            
            # Receive and process the output
            iptv_output = remote_conn.recv(65535).decode('utf-8')  # Decode bytes to string
            lines = iptv_output.splitlines()  # Split output into individual lines
            
            # Extract multicast IPs
            multicast_ips = []
            # Regex to match exactly 232.235.000.xxx format
            ip_pattern = re.compile(r'^232\.235\.000\.\d{3}')
            
            for line in lines:
                stripped_line = line.strip()
                # Skip empty lines, header, and separator line
                if not stripped_line or stripped_line.startswith('MVR Group') or stripped_line.startswith('---'):
                    continue
                # Extract IP using regex or split by whitespace
                match = ip_pattern.match(stripped_line)
                if match:
                    multicast_ips.append(match.group())
                # Alternative: split by whitespace and take first element (if output format is consistent)
                # ip = stripped_line.split()[0]
                # if ip.startswith('232.235.000.'):
                #     multicast_ips.append(ip)
            
            # Format the output as requested
            formatted_output = "Multicast IP\n------------\n" + "\n".join(multicast_ips)
            
            # Clean up the SSH session
            remote_conn.send("end\n")
            remote_conn.send("exit\n")
        finally:
            # Ensure the connection is closed even if an error occurs
            remote_conn_pre.close()
        
        # Pass the formatted output to your template for display
        return render(request, 'your_template.html', {'multicast_output': formatted_output})
    
    # Handle GET request or other cases
    return render(request, 'your_template.html')

Key Changes Explained:

  1. Decode Byte Output: The recv() method returns bytes, so we use decode('utf-8') to convert it to a human-readable string.
  2. Line-by-Line Processing: Split the output into lines with splitlines() to process each entry individually.
  3. IP Extraction:
    • Used a regex pattern to precisely match your target multicast IP format (232.235.000.xxx).
    • Alternatively, if the output format is always consistent, you can split each line by whitespace and take the first element (commented out in the code).
  4. Proper SSH Session Cleanup: Moved the end and exit commands outside the loop, and added a finally block to ensure the connection is closed even if an error occurs.
  5. Formatted Output: Built the exact string format you need, which can be passed to your Django template for display.

Frontend Display (Example Template):

In your template (your_template.html), you can display the formatted output with a button trigger:

<form method="post">
    {% csrf_token %}
    <button type="submit" name="RETRIEVE">Retrieve Multicast IPs</button>
</form>

{% if multicast_output %}
<pre>{{ multicast_output }}</pre>
{% endif %}

The <pre> tag preserves the line breaks and formatting so your output looks exactly as you specified.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:33:28