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:
- Decode Byte Output: The
recv()method returns bytes, so we usedecode('utf-8')to convert it to a human-readable string. - Line-by-Line Processing: Split the output into lines with
splitlines()to process each entry individually. - 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).
- Used a regex pattern to precisely match your target multicast IP format (
- Proper SSH Session Cleanup: Moved the
endandexitcommands outside the loop, and added afinallyblock to ensure the connection is closed even if an error occurs. - 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
相关产品推荐
相关产品推荐

