-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlog-bandwidth.sh
executable file
·59 lines (54 loc) · 1.71 KB
/
log-bandwidth.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#!/usr/bin/env bash
## log-bandwidth.sh
# Save current bandwidth stats to a log.
log_location="$(get-config "log-bandwidth/log-location" \
-what-do "where to save the log")" || exit 1
IFS=$'\n'
interfaces=( $(ip addr | grep -E '^[0-9]+: ' |
sed -r 's/[0-9]+: ([^:]+):.*/\1/g') ) || exit 1
# Make sure the log location exists.
mkdir -p "$(dirname "$log_location")"
touch "$log_location"
## Usage: log [options] [stuff to log]
# Logs stuff to $log_location. Accepts the same arguments as echo.
log() {
echo "$@" >> "$log_location"
}
## Usage: get-bytes interface direction
# Gets the number of bytes of bandwidth use for interface in
# direction, since "ip" doesn't have custom output format
# control. Direction can be RX or TX.
get-bytes() {
local if="$1"
local dir="$2"
local result
# Get stats
result="$(ip -s link show "$if")"
if [ "$?" = "0" ]; then
# Find right line
result="$(echo "$result" | grep -E -A1 "^ *$dir: bytes .*\$")"
# Strip preceding wrong line
result="$(echo "$result" | tail -n1)"
# Get just the numbers
result="$(echo "$result" | grep -E -o -m1 "[0-9]+")"
# Limit to first match (byte count)
result="$(echo "$result" | head -n1)"
# Finally output nonzero result
if [ "$result" != "0" ]; then
echo "$result"
return 0
fi
fi
return 1
}
log "$(date -Iseconds)"
for interface in "${interfaces[@]}"; do
for direction in RX TX; do
bytes="$(get-bytes "$interface" "$direction")"
if [ "$?" = "0" ]; then
log -n "$interface $direction: "
log "$bytes bytes"
fi
done
done
log # newline