Automatic OpenWRT Updater

 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
##!/bin/bash

#
# Automatic OpenWRT manteinance:
# - Upgrades all packages
# - Upgrades OpenWRT version to latest stable
# 

# Find target and id from
# https://downloads.openwrt.org/releases/23.05.5/.overview.json
target=ath79/generic    # CHANGEME   
id=tplink_archer-c7-v5  # CHANGEME
router=root@192.168.1.2 # CHANGEME

# Get upstream version
stable_version=$(curl 'https://downloads.openwrt.org/.versions.json' 2>/dev/null | jq '.stable_version' | cut -d '"' -f 2)

# Get router version
router_version=$(ssh ${router} cat /etc/os-release | grep "VERSION=" | cut -d "\"" -f 2)

# CHeck if router version is latest stable
if [ "${router_version}" == "${stable_version}" ]; then
  echo "[+] Already running latest OpenWRT (${stable_version})"
  echo "[+] Updating OpenWRT packages"
  ssh ${router} "opkg update && opkg list-upgradable | cut -f 1 -d ' ' | xargs opkg upgrade"
  exit 0
else
  echo "[+] Updating OpenWRT ${router_version} -> ${stable_version}"
fi

# If not, proceed to upgrade the router

# Download the sysupgrade file

file=$(ls openwrt-${stable_version}* | cut -d ' ' -f 1)

if [ ! -f ${file} ]; then
  wget -q https://downloads.openwrt.org/releases/${stable_version}/targets/${target}/openwrt-${stable_version}-${target//\//-}-${id}-squashfs-sysupgrade.bin
  file=$(ls openwrt-${stable_version}* | cut -d ' ' -f 1)
  echo "[+] Downloaded ${file}"
fi

# Check download integrity against OpenWRT listed one
file=$(ls openwrt-${stable_version}* | cut -d ' ' -f 1)
sha256=$(sha256sum ${file} | cut -d ' ' -f 1)
check=$(curl 2>/dev/null  "https://downloads.openwrt.org/releases/${stable_version}/targets/${target}/profiles.json" | grep -c ${sha256})
if [ "${check}" -eq "0" ]; then
  echo "[+] Corrupted download"
  exit 1
else

  echo "[+] Integrity check passed (download)"
fi

# Copy sysupgrade file to the router
echo "[+] Sending upgrade file to the router"
scp -O ${file} ${router}:/tmp/${file}

# Check if file got corrupted during send
router_sha256=$(ssh ${router} "sha256sum /tmp/${file} | cut -d ' ' -f 1")

echo ${router_sha256}

if [ "${sha256}" != "${router_sha256}" ]; then
  echo "[+] Corrupted file in the router"
  exit 1
else
  echo "[+] Integrity check passed (router)"
fi

# Update all router packages before a sysupgrade
echo "[+] Updating OpenWRT packages"
ssh ${router} "opkg update && opkg list-upgradable | cut -f 1 -d ' ' | xargs opkg upgrade"

# Perform sysupgrade on router
echo "[+] Upgrading OpenWRT"
ssh ${router} "sysupgrade /tmp/${file}"