A bash script for listing the number of registered users on a Matrix homeserver

I wanted a quick and easy way to see how many registered users there are on my Matrix homeserver without having to log in to the admin interface, so I wrote a short bash script.

#!/bin/bash

# Lists the number of registered users on a Matrix homeserver according to
# https://matrix-org.github.io/synapse/develop/admin_api/user_admin_api.html#list-accounts
# Version 1.1, 2022-02-20

echo "Please enter your admin access token"
read -s TOKEN
if [[ -z "$TOKEN" ]]
then
  while [[ -z "$TOKEN" ]]
  do
    echo "No admin access token entered"
    echo "Please enter your admin access token"
    read -s TOKEN
  done
fi
users=$(curl --silent -H "Authorization: Bearer $TOKEN" \
https://<HOMESERVER>/_synapse/admin/v2/users?from=0&limit=100000&guests=false)

if [[ "$users" =~ "M_UNKNOWN_TOKEN" ]]
then
  echo "ERROR: Invalid access token"
  exit 1
elif [[ "$users" =~ "error" ]]
then
  echo "ERROR: An error occured"
  echo $users
exit 2
fi

numberOfUsers=$(echo "$users" | tail -c 8 | grep -Eo "[0-99999]+")

echo "There are" $numberOfUsers "users on <HOMESERVER> (non-deactivated) \
as of" $(date)
echo "There are" $numberOfUsers "users on <HOMESERVER> (non-deactivated) \
as of" $(date) >> users.txt

To use it, replace <HOMESERVER> with the address of your own server, e.g. hingst.net. Here’s what it does:

read -s TOKEN asks the user for an input, where you enter your admin access token. The input is sent with the curl request to the matrix server (according to the Synapse API), excluding guests.

As the JSON response includes the number of users last in the response I simply cut the last 8 bytes and search for the number of users with grep -Eo (-E for extended regexp and -o for non.empty parts). The output is stored in the variable numberOfUsers, which is written to the console as well as a users.txt file.

The final output looks something like,

There are XY users on Hingst.net (non-deactivated) as of fre 14 jan 2022 16:15:14 CET

It works, but the code is perhaps not the best 😉

The JSON response will be quite long if you try to fetch thousands of users at once, so not sure if the code works then. I’m also not entirely sure this code is 100% safe if a user has an odd nickname, so use on your own risk.

Updated 2022-05-24

Lämna en kommentar

Din e-postadress kommer inte publiceras. Obligatoriska fält är märkta *