Personal Status Page | Original

Home 2025.01

It looks like the version of vnstat you installed does not support the -u parameter. Let’s proceed with the correct steps to configure vnstat and set up the bandwidth monitoring API.

Step 1: Configure vnstat

Initialize vnstat for your network interface:

sudo vnstat -i eth0

Step 2: Wait for Data Collection

vnstat needs time to gather data. Check the status periodically:

sudo vnstat -l

After some time, verify data collection:

sudo vnstat -d

Step 3: Create an API to Expose Bandwidth Data

Install Flask:

pip install Flask

Create a Python script (bandwidth_api.py):

from flask import Flask, jsonify
from flask_cors import CORS
import subprocess

app = Flask(__name__)
CORS(app)  # Enable CORS for all routes

@app.route('/bandwidth', methods=['GET'])
def get_bandwidth():
    # Run the vnstat command to get the 5-minute interval traffic statistics for eth0
    result = subprocess.run(['vnstat', '-i', 'eth0', '-5', '--json'], capture_output=True, text=True)
    data = result.stdout

    # Return the captured data as a JSON response
    return jsonify(data)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)

Run the script:

python bandwidth_api.py

Step 4: Integrate with Your Blog

Use the following HTML and JavaScript to fetch and display the bandwidth data:

document.addEventListener('DOMContentLoaded', function () {
    fetch('https://www.lzwjava.xyz/bandwidth')
        .then(response => response.json())
        .then(data => {
            var bandwidthData = JSON.parse(data);

            // Create a container for the times
            var timesContainer = document.createElement('div');

            var currentUtcTime = new Date();
            var currentLocalTime = new Date(currentUtcTime.getTime());

            var pUtcTime = document.createElement('p');
            pUtcTime.textContent = `UTC Time: ${currentUtcTime.toUTCString()}`;
            timesContainer.appendChild(pUtcTime);

            var pLocalTime = document.createElement('p');
            pLocalTime.textContent = `My Local Time: ${currentLocalTime.toString()}`;
            timesContainer.appendChild(pLocalTime);

            // Append the times container to the status div
            document.getElementById('status').appendChild(timesContainer);

            // Create a table
            var table = document.createElement('table');
            table.border = '1';
            table.style.borderCollapse = 'collapse';
            table.style.width = '100%';

            // Create table header
            var thead = document.createElement('thead');
            var tr = document.createElement('tr');
            var headers = ['Time', 'Traffic (KB/s)', 'Status'];
            headers.forEach(headerText => {
                var th = document.createElement('th');
                th.textContent = headerText;
                tr.appendChild(th);
            });
            thead.appendChild(tr);
            table.appendChild(thead);

            // Create table body
            var tbody = document.createElement('tbody');

            // Process traffic data
            var fiveMinuteData = bandwidthData.interfaces[0].traffic.fiveminute.reverse();
            fiveMinuteData.forEach(interval => {
                var tr = document.createElement('tr');

                var dataTime = new Date(Date.UTC(interval.date.year, interval.date.month - 1, interval.date.day, interval.time.hour, interval.time.minute));
                var timeDifference = Math.round((currentUtcTime - dataTime) / (1000 * 60)); // Time difference in minutes

                var tdTimeDifference = document.createElement('td');
                tdTimeDifference.textContent = timeDifference + ' mins ago';
                tr.appendChild(tdTimeDifference);

                var averageTraffic = (interval.rx + interval.tx) / 2; // Calculate average of RX and TX
                var tdTrafficKBs = document.createElement('td');
                var trafficKBs = (averageTraffic / (5 * 60 * 1024)).toFixed(2); // Convert to KB/s
                tdTrafficKBs.textContent = trafficKBs;
                tr.appendChild(tdTrafficKBs);

                var tdStatus = document.createElement('td');
                tdStatus.textContent = trafficKBs > 5 ? 'Online' : 'Offline';
                tdStatus.className = trafficKBs > 5 ? 'status-online' : 'status-offline';
                tr.appendChild(tdStatus);

                tbody.appendChild(tr);
            });
            table.appendChild(tbody);

            // Append the table to the status div
            document.getElementById('status').appendChild(table);
        })
        .catch(error => {
            console.error('Error fetching bandwidth data:', error);
        });
});

Replace http://your-droplet-ip:5000/bandwidth with your droplet’s IP address.

Additional Considerations

By following these steps, you can create a status page on your blog that indicates whether you are online based on the bandwidth usage of your DigitalOcean droplet.


Original. Curating and sharing still takes effort. If you find it useful, feel free to donate. WeChat: @lzwjavaWeChat QR · X: @lzwjava · Say hi 👋

Back Donate