
Recall first from Dashboards with Streamlit
- A Streamlit script reruns top to bottom on every widget interaction; widget calls return the reader's current selection
- st.cache_data caches a function's return value across reruns and sessions, keyed by its arguments; st.session_state is per-browser-session storage
- streamlit run app.py serves the app on http://localhost:8501 by default
Serving the dashboard safely
5 min readIn the previous lesson you built a Streamlit dashboard locally. This lesson serves it safely on the Pi with localhost binding and basic auth, and connects capture, parsing and storage into one data pipeline.
Start with the default, because the default is the unsafe case. streamlit run app.py starts a web server on port 8501 and, with no address configured, accepts connections on every interface: your laptop, the Pi, and anyone else on the lab network can open it. There is no login. For a dashboard that shows test results that is tolerable; for one that can trigger actions or expose device data it is not. The first fix costs one flag:
streamlit run app.py --server.address 127.0.0.1 --server.port 8501
passing the loopback address 127.0.0.1 to bind(2) so the listening socket accepts connections only from processes on the same machine changes who can reach the port at the kernel level, not by a firewall rule you might forget. Verify it with ss -ltn. In a real test on Ubuntu 24.04 with Streamlit 1.67.0, a plain streamlit run app.py --server.headless true showed LISTEN 0 2048 *:8501 *:*, and with --server.address 127.0.0.1 the same line read LISTEN 0 2048 127.0.0.1:8501 0.0.0.0:* (the exact column layout on your machine will differ). From another machine the connection is now refused, which is exactly what you want.
But you still need to see the dashboard from your laptop. The safe answer is an ssh -L opens a listening port on your machine and forwards every connection through the encrypted SSH session to a chosen address and port on the far side:
ssh -N -L 8501:127.0.0.1:8501 pi@raspberrypi.local
-N means "no remote command, just forward". Now http://localhost:8501 in your laptop's browser reaches the Pi's dashboard, the traffic is encrypted by SSH, and the dashboard's port stays invisible to the rest of the network. Authentication is your SSH login, which you already have. On an untrusted or shared network, this is the whole solution: bind to localhost, tunnel in, done.
Sometimes you want the whole lab team to open the dashboard without SSH accounts. Then you need a a server that accepts client connections and forwards them to a backend service, adding TLS, authentication or logging on the way in front of Streamlit. Streamlit has no username-and-password login of its own, so basic auth lives in nginx:
sudo apt install nginx apache2-utils
sudo htpasswd -c /etc/nginx/.htpasswd viewer
htpasswd prompts for a password and writes a hashed entry (the -b option takes the password on the command line instead, which is handy in a test but leaves it in your shell history). A site file in /etc/nginx/sites-available/, symlinked into sites-enabled/, then sudo nginx -t && sudo systemctl reload nginx:
server {
listen 80;
server_name raspberrypi.local;
auth_basic "Lab dashboard";
auth_basic_user_file /etc/nginx/.htpasswd;
location / {
proxy_pass http://127.0.0.1:8501;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
}
}
The two Upgrade and Connection headers are not optional decoration: Streamlit pushes every update over a WebSocket, and without those headers the proxy breaks the WebSocket handshake and the page loads but never updates. This configuration was run for real with nginx 1.24.0 and Streamlit bound to 127.0.0.1: a request with no credentials got 401, a wrong password got 401, and the right one got 200. A WebSocket connection to /_stcore/stream through nginx succeeded with the two headers, and after deleting the two proxy_set_header lines for Upgrade and Connection it was rejected (server rejected WebSocket connection: HTTP 200, where a handshake needs 101). Two practical notes: a fresh Ubuntu nginx also ships a default site that answers on port 80, so remove its link from sites-enabled/ or request the server name you configured; and the base64 of viewer:s3cret is dmlld2VyOnMzY3JldA==, which decodes back to the password with one call, as the next box explains.
HTTP basic auth sends the username and password Base64-encoded on every request. Base64 is an encoding, not encryption: anyone capturing traffic on the network can decode it. Use basic auth only on a trusted lab LAN, or put TLS in front of it. On anything else, prefer the SSH tunnel.
A dashboard started in an SSH session dies when the session closes. On the Pi, put the same command in a systemd service with --server.headless true (which stops Streamlit trying to open a browser), for example ExecStart=/home/pi/venv/bin/streamlit run /home/pi/dash/app.py --server.address 127.0.0.1 --server.headless true, so it restarts on boot and survives logout.
Capture, parse, store: one pipeline
3 min readYou now have two halves of a system: lessons S03A and S03B taught you to parse logs and frames into typed records and analyse them, and the previous lesson taught you to display dataframes. The missing piece is the contract between them. The rule that makes a lab tool trustworthy: the dashboard never captures, and the capture never renders. They meet only at the a durable file or database that parsed records are written to and every consumer reads from.
Each stage has one job and one output:
Capture: scapy's
sniff()orrdpcap()writes a .pcap; pyserial writes a raw boot log. Raw bytes, timestamped, never edited.Parse: the regex-and-dataclass parsers from S03A (or scapy's dissectors from S06B2) turn raw artifacts into typed rows: sequence number, latency in milliseconds, boot milestone, seconds since reset.
Store: rows go into SQLite via the standard-library
sqlite3module, tagged with a run id so repeated experiments stay separate.Dashboard: Streamlit opens the database read-only and renders charts. A rerun re-reads the store; it never sends a packet.
Why files and a database instead of function calls? Because the stages run at different times and different rates. Capture runs once per experiment, maybe for ten minutes with the device attached. The dashboard reruns its whole script on every widget click. If the dashboard captured on rerun, every slider move would poke the hardware. With a store in between, you can also re-plot yesterday's run, diff two runs, or parse the same pcap twice with a fixed parser without touching the device again.
A schema for latency runs is two tables:
CREATE TABLE IF NOT EXISTS runs (
run_id INTEGER PRIMARY KEY,
started TEXT NOT NULL,
target TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS latency (
run_id INTEGER NOT NULL REFERENCES runs(run_id),
seq INTEGER NOT NULL,
rtt_ms REAL,
timed_out INTEGER NOT NULL DEFAULT 0
);
rtt_ms is nullable on purpose: a request that timed out is still a result, stored as a row with timed_out = 1 and no latency. Dropping timeouts silently would make a flaky device look fast, because only the successes would remain in the statistics.
The writer side is plain sqlite3:
import sqlite3
def save_run(con, rows, target, started):
cur = con.execute(
"INSERT INTO runs(started, target) VALUES (?, ?)",
(started, target))
run_id = cur.lastrowid
con.executemany(
"INSERT INTO latency(run_id, seq, rtt_ms, timed_out) "
"VALUES (?, ?, ?, ?)",
[(run_id, seq, rtt, int(rtt is None)) for seq, rtt in rows])
con.commit()
The reader side opens the same file with a read-only URI, so a bug in the dashboard cannot corrupt an experiment, and caches the query so ten widget clicks do not mean ten full table scans:
import sqlite3
import pandas as pd
import streamlit as st
@st.cache_data(ttl=10)
def load_latency():
con = sqlite3.connect("file:lab.db?mode=ro", uri=True)
df = pd.read_sql_query(
"SELECT seq, rtt_ms FROM latency ORDER BY seq", con)
con.close()
return df
SQLite handles this pattern well: one capture process writes a run, and any number of dashboard sessions read. Keep writes in the capture stage only. If you later need a live writer and reader at the same moment, enable WAL mode (PRAGMA journal_mode=WAL) so readers are not blocked during a commit.
Replay a capture and chart the latency
4 min readThe practical that ties the module together: take a capture of requests, replay it against a device, measure how long each response takes, and watch the result in the dashboard. Replaying a known capture instead of generating fresh traffic makes runs comparable: same requests, same order, so a latency change points at the device or the network, not at your stimulus.
scapy reads the capture with rdpcap() and sr1() sends one packet and waits for its answer. Wrap each send in time.perf_counter() and you have a per-request round trip:
from scapy.all import IP, rdpcap, sr
rows = []
for seq, pkt in enumerate(rdpcap("requests.pcap")):
answered, _ = sr(pkt[IP], timeout=2, verbose=0)
if answered:
sent, reply = answered[0]
rtt = float((reply.time - sent.sent_time) * 1000.0)
else:
rtt = None
rows.append((seq, rtt))
Run it with sudo (scapy needs raw sockets), feed rows to save_run() from the previous section, and the run is in the store. Without a reply sr() returns an empty answered list after the two-second timeout, which becomes a timed_out row rather than a missing measurement.
Two details come from failures in a real test, and both matter for the numbers. First, sr and sr1 send at layer 3, so give them the IP part: a pcap captured with tcpdump stores whole Ethernet frames, and in the test sr1(pkt) on such a frame timed out for all five requests, so every row would have been stored as a timeout. pkt[IP] fixed it (a pcap that you wrote yourself from IP()/ICMP() packets has no Ethernet layer, and pkt[IP] still works). Second, do not time the call with time.perf_counter() around sr1: on the loopback interface, where the real echo round trip is a few hundredths of a millisecond, that stopwatch read 12.5 to 19.4 ms per request, because it also counts everything scapy does to set up the socket and route the packet. The reply.time - sent.sent_time difference read 0.043 to 0.058 ms for the same requests. The float() turns scapy's decimal timestamp type into a plain number that sqlite3 can store.
A replayed capture contains real addresses and real payloads. Point it only at devices you own, on a network you control. Replaying captured traffic at someone else's device or network is indistinguishable from an attack. If you just want to blast packets at wire speed without measuring answers, tcpreplay --intf1=eth0 requests.pcap exists for that, but it reports nothing about responses, which is why the sr1() loop above is the right tool here.
The dashboard over the store is a few lines on top of load_latency():
df = load_latency()
st.line_chart(df, x="seq", y="rtt_ms")
st.metric("p95 latency (ms)", round(df["rtt_ms"].quantile(0.95), 2))
st.metric("timeouts", int(df["rtt_ms"].isna().sum()))
The line chart shows the shape of the run (a device that warms up, a periodic stall), the p95 metric summarises the tail using the percentile tools from S03B4, and the timeout count keeps the failures visible. Null latencies simply do not plot, while the metric still counts them. Run against a test database with four rows (0.5, NULL, 0.7 and 0.6 ms), Streamlit's headless test runner showed a p95 latency (ms) metric of 0.69 and timeouts of 1, and opening the database with mode=ro made an INSERT fail with OperationalError: attempt to write a readonly database.
The same pipeline serves boot data with no new machinery. The capture stage saves the serial boot log; the parse stage uses the S03A regex-and-dataclass approach to extract milestone rows (boot id, milestone name, seconds since reset); the store gets a milestones table next to latency. The dashboard then charts each milestone's duration across boots, so a kernel change that adds time to driver probe shows up as one bar growing while the others hold still. Capture, parse, store, render: you built the pattern once, and every future measurement in this course plugs into it.
That pattern is also the seed of the capstone. The next lesson, "The devkit brief and architecture", takes these pieces (protocol tooling, parsers, a store and a dashboard) and asks you to assemble them into one deliverable tool with a defined scope.
Key takeaways
- Streamlit listens on port 8501 and, left unconfigured, on every interface; --server.address 127.0.0.1 makes it reachable only from the same machine
- Basic auth belongs in a reverse proxy in front of Streamlit, and over plain HTTP its Base64 credentials are readable by anyone sniffing the network
- A pipeline of capture, parse, store and dashboard stages communicates through files and a database, so dashboard reruns never touch the hardware
- Timeouts must be stored as rows, not dropped, or the latency statistics only describe the requests that succeeded
Reflect
- Explain to a colleague, in two sentences: bind a Streamlit server to 127.0.0.1 and reach it from another machine through an SSH local forward
- Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
- What surprised you when you ran the commands yourself?
On a real board
Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.
References and further reading
- Man pagessh(1): the OpenSSH client, including -L local forwarding
- Man pagebind(2): binding a socket to an address
- Man pagess(8): dumping socket statistics
- Man pagetcp(7): the TCP protocol and listening sockets
- Documentationnginx: WebSocket proxying
Official documentation first. Links checked when the lesson was published.