sodcalculator

10 Tech How-To

Show Live Network Data in Browser: Step-by-Step

Guide 10-47079 · Updated · Step by step

This guide shows you how to display fresh network operations data—like interface traffic, CPU load, or latency—directly in a web browser using a simple Python web server and a lightweight JavaScript charting library. You’ll set up a small API that reads live metrics and a frontend that updates automatically every few seconds, giving you a real-time dashboard without heavy monitoring tools.

What You’ll Need

  • A computer with Python 3 installed (check with python3 --version).
  • Access to the network device or system you want to monitor (e.g., router, switch, server).
  • Basic familiarity with the command line and editing text files.
  • Optional: a tool like snmpwalk or curl to fetch metrics from your device, but we’ll use a simple placeholder for demo.

Step-by-Step

  1. Create a project folder. Open a terminal and run mkdir netdashboard && cd netdashboard.
  2. Write a Python script that collects data. Create a file named collector.py. Start with a function that returns a dictionary of metrics—for example, interface bytes in/out and CPU usage. For a real device, you’d replace this with SNMP calls or reading /proc/net/dev on Linux. Here’s a simple version that simulates changing values:
  3. import random, time
    
    def get_metrics():
        return {
            'timestamp': time.time(),
            'rx_bytes': random.randint(1000, 9999),
            'tx_bytes': random.randint(1000, 9999),
            'cpu': random.randint(1, 100)
        }
  4. Create a web server with an API endpoint. In the same folder, create server.py. Use Python’s built-in http.server to serve static files and a /api/metrics endpoint that returns the data as JSON. Here’s a minimal example:
  5. from http.server import HTTPServer, BaseHTTPRequestHandler
    import json, collector
    
    class Handler(BaseHTTPRequestHandler):
        def do_GET(self):
            if self.path == '/api/metrics':
                data = collector.get_metrics()
                self.send_response(200)
                self.send_header('Content-type', 'application/json')
                self.end_headers()
                self.wfile.write(json.dumps(data).encode())
            else:
                self.send_response(200)
                self.send_header('Content-type', 'text/html')
                self.end_headers()
                with open('index.html', 'rb') as f:
                    self.wfile.write(f.read())
    
    if __name__ == '__main__':
        HTTPServer(('localhost', 8000), Handler).serve_forever()
  6. Create the HTML page with a chart. Make index.html in the same folder. Include a charting library like Chart.js from a CDN, and write JavaScript to fetch the API every 2 seconds and update the chart. Below is a working example that shows a line chart of received bytes and CPU.
  7. <!DOCTYPE html>
    <html>
    <head>
      <title>Network Dashboard</title>
      <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    </head>
    <body>
      <canvas id="myChart" width="400" height="200"></canvas>
      <script>
        const ctx = document.getElementById('myChart').getContext('2d');
        const chart = new Chart(ctx, {
          type: 'line',
          data: {
            labels: [],
            datasets: [{
              label: 'RX bytes',
              data: [],
              borderColor: 'blue',
              fill: false
            }, {
              label: 'CPU %',
              data: [],
              borderColor: 'red',
              fill: false
            }]
          },
          options: { scales: { y: { beginAtZero: true } } }
        });
    
        async function update() {
          const res = await fetch('/api/metrics');
          const data = await res.json();
          const time = new Date(data.timestamp * 1000).toLocaleTimeString();
          chart.data.labels.push(time);
          chart.data.datasets[0].data.push(data.rx_bytes);
          chart.data.datasets[1].data.push(data.cpu);
          if (chart.data.labels.length > 20) {
            chart.data.labels.shift();
            chart.data.datasets.forEach(ds => ds.data.shift());
          }
          chart.update();
        }
        setInterval(update, 2000);
        update();
      </script>
    </body>
    </html>
  8. Run the server. In the terminal, execute python3 server.py. Leave it running.
  9. Open your browser. Go to http://localhost:8000. You should see the chart updating every couple of seconds with new data points.

Common Mistakes

  • Using the wrong Python version. If python3 isn’t found, try python or install Python 3.
  • Port already in use. If you get an error binding to port 8000, change the port in the script (e.g., 8001) and update the URL.
  • Forgetting to close the HTML file. The server reads index.html every time, so if it’s malformed, the page won’t load.
  • Not handling CORS. If you open the HTML file directly (double-click) instead of via the server, the fetch will fail due to CORS. Always use the server.

Tips

  • Use real data. Replace the random values with actual metrics from /proc/net/dev on Linux, or query your router via SNMP using a library like pysnmp.
  • Add more charts. Create separate canvases for different metrics like latency or packet loss.
  • Optimize performance. Instead of fetching every 2 seconds, fetch every 5 or 10 seconds to reduce load.
  • Keep history. Store metrics in a list and display a larger window (e.g., last 100 points).

Troubleshooting

  • Page loads but no data updates. Check the browser console (F12) for errors. Common issues: the API path is wrong, or the JSON structure doesn’t match what the chart expects.
  • Chart shows “Cannot read properties of undefined”. This usually means the API returned an error. Test http://localhost:8000/api/metrics directly in the browser to see the JSON.
  • Server crashes on import. Make sure collector.py is in the same directory and has no syntax errors. Run python3 collector.py to test it standalone.
  • Chart is blank. Ensure the canvas has a defined height and width, or set responsive options in Chart.js.

Frequently Asked Questions

Can I use this with a remote network device?

Yes, but you need to modify the collector to fetch data via SNMP or an API from that device. Ensure your Python environment has the necessary libraries (e.g., pysnmp) and network access.

How do I make the dashboard accessible to other computers?

Change the server to listen on 0.0.0.0 instead of localhost, and use your computer’s IP address in the browser. Be careful with firewalls and security—don’t expose it to the internet without authentication.

Can I use a different charting library?

Absolutely. Chart.js is just one option. You can use D3.js, ECharts, or even plain CSS bars. The key is to update the DOM with new data.

How do I stop the server?

Press Ctrl+C in the terminal where the server is running.

Why does the chart reset when I refresh the page?

Because the data is only stored in the browser’s memory. If you want persistence, store the data in a backend database or use localStorage.

Is it safe to run this on a production network?

It depends. If you’re only reading metrics, it’s generally safe, but avoid exposing the server publicly without authentication. For production, consider using existing tools like Grafana or PRTG.

Related

General steps for current mainstream versions; menus can differ by device and version. See the disclaimer or report an error.

More in this bed

The whole Tech How-To bed →