Auto Reboot Ubiquiti Devices with

Most of the heavy lifting is done by the script. All you need is the IP addresses for the access points. The script will figure out the connected devices, reboot them first, then reboot the AP.

Here is a quick run down of the steps we need to perform.

  1. Create list of AP’s and put them into an ap.lst file
  2. Install script
  3. Configure usernames and passwords to use with
  4. Setup crontab to automatically run

Create list of AP’s and put them into an ap.lst file

This is really as simple as creating the ap.lst file and filling it with the access point IP addresses. One per line. The script uses wstalist to discover connected devices.

nano ap.lst

Install script

Installing the script is really hard. 2 lines to get setup.

chmod +x ./

More information can be found here.

Setup usernames and passwords to use with ubntmod.shd

When you first run without the -y option, it should prompt you to setup usernames and passwords to use. After this is setup, the script automatically reads from the config file for future use.

You can manually modify the ubntmod.conf file update any usernames or passwords.

Example contents of ubntmod.conf file.

unpw=( "ubnt,ubnt"

Setup crontab to automatically run

Open up crontab with

crontab -e 

Configure the time. Refer to here for crontab date syntax

10 1 * * * cd /home/bob/ && ./ -A

That’s it. Should be good to go.

Add directory to path in Linux

Adding a directory to your path is really easy.

The following command adds the ~/script_folder to our PATH paths. Once run, we’ll be able to call any script in the script folder like it was a system utility.


If you would like to always be able to call any file in your scripts folder, add the above command to your ~/.bashrc file.

You may need to restart your session for it to work.

Get list of IP DHCP Leases from Mikrotik RouterOS Command Line

Sometimes it is nice to have a list of just the IP addresses and the hostname or mac address. Can be especially helpful when you are trying to get a list of devices to do a bulk update in LibreNMS. Helpful LibreNMS links for renaming and showing down devices

we are going to run the command to pull the DHCP information and then use Unix utilities to parse the data out.

Replace dhcp8 with the correct dhcp server in the mikrotik.

First, SSH into your Mikrotik router.

ssh user@mikrotik

Next we’ll want to go to the ip dhcp-server lease directory

/ip dhcp-server lease

Now we can run the following command to loop through and pull out all the info we need.
You can change the info like “mac-address” for something like “status”. You can use Tab to see what options are available. Just delete mac-address and hit tab twice.

:foreach i in=[find] do={ :put ([get $i address].",".[get $i mac-address].",".[get $i server].",".[get $i host-name ])}

Found the above helpful info from the following pdf file.

Simple SH Ping script to scan a /24

This is a very simple ping script I created to run on a remote UniFi device to scan for other IP addresses on it’s network. It works on SH environments as well as Bash.

Paste the script in a file and then

chmod +x

run like so, replacing 192.168.1. with the IP range you want to scan.

sh 192.168.1.

# simple ping scan utility

# i.e. 192.168.0.

while [ $ip -ne 255 ] 
  ping -w1 $ipFirstPart${ip} | grep "64 bytes from"

LibreNMS backup script

You should be able to copy and paste the following in a file and then execute from cron. Should work out of the box, but you can change the backup directory and the path if needed/wanted.


# LibreNMS backup script
# Jan 1, 2019

lDate=`date +%Y%m%d-%H%M`       # local date + hour minute
dDate=`date +%Y%m%d`            # todays date

# If you have the script, you can trigger a backup notification
ALERT="/home/admin/ -b"

# Directory to backup to

# MySQL settings for tar and sqldump

# Directory that contains data

# tar LibreNMS dir
# tar SQL dir "the whole thing with the innode files
# sql dump of the db for extra redundancy

if [ -d ${bDir} ]; then
echo "backup dir exist, starting to backup"
        echo "backup dir not available.  Quiting"
        exit 1

${ALERT} "Starting backup for ${bName} - `date`"

systemctl stop mariadb httpd
# LibreNMS data backup
tar -zcvf ${bDir}/${lDate}-${bName}.tgz ${dDir}
if [ $? -eq 0 ]; then
        echo "Tar succesfully backed up ${bDir}"
        echo "Tar failed while trying to backup ${dDir}"
        echo " ${lDate} - Tar failed while trying to backup ${dDir}" >> ${LOG}
        ${ALERT} "${lDate} - Tar failed while trying to backup ${dDir}"

# MySQL data backup
tar -zcvf ${bDir}/${lDate}-${bName}-mysql.tgz ${sqlDir}
if [ $? -eq 0 ]; then
        echo "Tar succesfully backed up ${sqlDir}"
        echo "Tar failed while trying to backup ${sqlDir}"
        echo " ${lDate} - Tar failed while trying to backup ${sqlDir}" >> ${LOG}
        ${ALERT} "${lDate} - Tar failed while trying to backup ${sqlDir}"

systemctl start mariadb httpd
sleep 5

 # SQL dump
mysqldump -u ${sqlUN} -p'4rfvBHU8!' ${sqlDB} > ${bDir}/${lDate}-${bName}.sql
if [ $? -eq 0 ]; then
        echo "MySQL DB dumped"
        echo "Ran into error while doing sql dump"
        echo "${lDate} - Ran into error while doing sql dump" >> ${LOG}
        ${ALERT} "${lDate} - Ran into error while doing sql dump"

echo "Removing old backups"
if ( ls ${bDir} | grep -q ${dDate} );then
        find ${bDir}/* -prune -mtime +31 -exec rm {} \;
        echo "Looks like there are no backup files!  Aborting!!!"
        ${ALERT} "${lDate} - Error: find failed to find any backup files in backup dir.  Aborting!!!"

${ALERT} "Finished backup for ${bName} - `date`"

Move multiple VLANs between two interfaces – Mikrotik

Move VLANs with foreach

Move all the VLANs under ether7 to ether6. Instead of an “=” sign, you can use a “~” to do a partial match.

foreach i in=[/interface vlan find where interface="ether7"] do={interface vlan set interface=ether6-master-local  $i } 

Move IP address to new port programmatically

Move ip address from ether6 to ether7. Change to the address and the find command will find it regardless of the port and assign it to ether6 or whichever port is specified.

ip address set interface=ether6-master-local [find address=""]

Using Delay

You can add a delay before a command runs by specifying delay and then the time to wait.

delay 60 

Use the ; to separate commands. Example below, wait 5 seconds then print the ip addresses.

delay 5 ; ip address print

Putting it all together

The following command/s will wait 60 seconds then move all the VLANs on ether7 to ether6 and then move the address to ether6.

delay 60 ; foreach i in=[/interface vlan find where interface="ether7"] do={interface vlan set interface=ether6-master-local  $i } ; ip address set interface=ether6-master-local [find address=""]

UBNTMOD check range of IP addresses and see if they resolve DNS

The following uses the script to check a device then report if it is resolving DNS or not. ip=”192.168.1.” specifies the first part of the ip, the “for ((i=1; i<=254;i++))” tells it to go from –, change the beginning and ending number if you want to change the ip range.

ip="192.168.1." && for ((i=10; i<=30;i++)); do if ( fping ${ip}$i -r1 | grep alive); then ./ -i ${ip}${i} -e ; else echo ${ip}$i not alive; fi ; done 

Broken out for easier reading.

for ((i=10; i<=30;i++))
if ( fping ${ip}$i -r1 | grep alive); then
./ -i ${ip}${i} -e
else echo ${ip}$i not alive

If the script is able to log into the device and resolve DNS you should get Resolves DNS

Linux night light script

The following script let you turn your screen brightness up/down, but also adjust the color for night time.

Copy and paste code below in a file

chmod +x

and run

./ on .5


export DISPLAY=$(w $(id -un) | awk 'NF > 7 && $2 ~ /tty[0-9]+/ {print $3; exit}')

display=`xrandr | grep "\ connected" | cut -d" " -f1`
# Check if brightness was specified.  If not, set screen to 50% brightness
if (echo $2 | grep [0-9]);then
elif (echo $1 | grep -q help);then
         echo "############"
         echo "Brightness variable not set, setting to fallback of 50%"
night_mode() {
   for disp in ${display}; do
     xrandr --output $disp --gamma $1 --brightness ${brightness}
  done }
# auto is for future development
# auto() {
# The idea behind auto is to setup something that can pull the actual sunrise/sunset times then automatically adjust the display.
# Ideally there would be an algorithm so it does it slowly over a period of time, say slightly change the color over 30 minutes.
# until the desired color limit is reached
# curl
# if (time > sunset && colorTemp != colorTempMin); then
# set color to current temp-1
# elif (time > sunrise && colorTemp != colorTempMax); then);
# set to full brightness and temp
# else
# unable to parse, skipping.
# fi
help() {
echo " Help for nightmode script.  
How to run script
./ on/off brightness
Turn nightmode on and set screen brightness to 75%
./ on .75
Turn night mode off and set screen brightness to 100%
./ off 1
case $1 in
  off) night_mode 1:1:1 1.0 ;;
  help) help ;;
  auto) auto ;;
  *) night_mode 1:1:0.5 ;;

Setup in crontab to automatically trigger when it gets night or morning

* 21 * * * ~/ on .5  # Turn on at night
* 7 * * * ~/ off 1  # Turn off in the morning

Raspberry Pi – Ping IP Address and Toggle LED

The following script is for monitoring if an IP address is reachable or not. If it becomes unavailable the script will turn on a LED that is plugged into one of the GPIO pins of the Raspberry Pi. View pinout here


# Script to ping ip address and turn on LED on if device is unreachable.
                                                                                                                                                                                                 nPin="18"  # Change if GPIO pin is different                                                                                                     
ledPin="gpio${nPin}"                                                                                                                                                                                                                            toPing=""  # Change to address you want to ping

echo "${nPin}" > /sys/class/gpio/export
echo "out" > /sys/class/gpio/${ledPin}/direction

if ( fping -r1 $toPing | grep -v alive ); then
         echo "Internet unreachable"
         # Turn on LED
         echo "1" > /sys/class/gpio/${ledPin}/value
         # Turn off LED 
         echo "0" > /sys/class/gpio/${ledPin}/value

Save script as and make it executable.

chmod +x

and run the script.


Run script in crontab

You can setup the script to run every minute using a crontab

crontab -e

Add the following line

*/1 * * * * /home/pi/

Should now execute the script every minute and not need any human interaction.

Auto renew ssl cert for UniFI and UniFi-Video

The following script was taken from here

Added unifi-video support. Script uses letsencrypt to get the cert and automatically updates the UniFi and UniFi-Video Keystores.

Would be a good idea to check and make sure the the UniFi-Video cameras reconnect and still work after running script.

Installing Let’s Encrypt

Install Let’s Encrypt with the following

sudo apt install letsencrypt

And generate a cert for your domain with

sudo certbot certonly -d

Executing Script to Renew Certificate

Copy the script at the bottom of this post and put it in a file called
Run the script to insert the cert into the UniFi and UniFi-Video services.

sudo ./ -e -d

You can run it with no or the -h argument to show the options and arguments to use.

./ -h

Setup Cron Job

You should be able to add the following to a cronjob to auto renew the certificate. Replace path to script and domain name.

30 2 * * * /root/ -r -d

UniFi SSL Cert Renew Script

#!/usr/bin/env bash
# Added support to do UniFi and UniFi controllers at the same time using the same cert.
# Original script from
# More info here 
# And here
# Modified script from here:
# Modified by: Brielle Bruns <>
# Download URL:
# Version: 1.7
# Last Changed: 09/26/2018
# 02/02/2016: Fixed some errors with key export/import, removed lame docker requirements
# 02/27/2016: More verbose progress report
# 03/08/2016: Add renew option, reformat code, command line options
# 03/24/2016: More sanity checking, embedding cert
# 10/23/2017: Apparently don't need the ace.jar parts, so disable them
# 02/04/2018: LE disabled tls-sni-01, so switch to just tls-sni, as certbot 0.22 and later automatically fall back to http/80 for auth
# 05/29/2018: Integrate patch from Donald Webster <fryfrog[at]> to cleanup and improve tests
# 09/26/2018: Change from TLS to HTTP authenticator

# Location of LetsEncrypt binary we use.  Leave unset if you want to let it find automatically


function usage() {
  echo "Usage: $0 -d <domain> [-e <email>] [-r] [-i]"
  echo "  -d <domain>: The domain name to use."
  echo "  -e <email>: Email address to use for certificate."
  echo "  -r: Renew domain."
  echo "  -i: Insert only, use to force insertion of certificate."

while getopts "hird:e:" opt; do
  case $opt in
    i) onlyinsert="yes";;
    r) renew="yes";;
    d) domains+=("$OPTARG");;
    e) email="$OPTARG";;
    h) usage

DEFAULTLEBINARY="/usr/bin/certbot /usr/bin/letsencrypt /usr/sbin/certbot
  /usr/sbin/letsencrypt /usr/local/bin/certbot /usr/local/sbin/certbot
  /usr/local/bin/letsencrypt /usr/local/sbin/letsencrypt
  /usr/src/letsencrypt/certbot-auto /usr/src/letsencrypt/letsencrypt-auto
  /usr/src/certbot/certbot-auto /usr/src/certbot/letsencrypt-auto
  /usr/src/certbot-master/certbot-auto /usr/src/certbot-master/letsencrypt-auto"

if [[ ! -v LEBINARY ]]; then
  for i in ${DEFAULTLEBINARY}; do
    if [[ -x ${i} ]]; then
      echo "Found LetsEncrypt/Certbot binary at ${LEBINARY}"

# Command line options depending on New or Renew.
NEWCERT="--renew-by-default certonly"
RENEWCERT="-n renew"

# Check for required binaries
if [[ ! -x ${LEBINARY} ]]; then
  echo "Error: LetsEncrypt binary not found in ${LEBINARY} !"
  echo "You'll need to do one of the following:"
  echo "1) Change LEBINARY variable in this script"
  echo "2) Install LE manually or via your package manager and do #1"
  echo "3) Use the included script to install it"
  exit 1

if [[ ! -x $( which keytool ) ]]; then
  echo "Error: Java keytool binary not found."
  exit 1

if [[ ! -x $( which openssl ) ]]; then
  echo "Error: OpenSSL binary not found."
  exit 1

if [[ ! -z ${email} ]]; then
  email="--email ${email}"

shift $((OPTIND -1))
for val in "${domains[@]}"; do
        DOMAINS="${DOMAINS} -d ${val} "


if [[ -z ${MAINDOMAIN} ]]; then
  echo "Error: At least one -d argument is required"
  exit 1

if [[ ${renew} == "yes" ]]; then

#if [[ ${onlyinsert} != "yes" ]]; then
if [[ ${onlyinsert} == "yes" ]]; then
  echo "Firing up standalone authenticator on TCP port 80 and requesting cert..."
  ${LEBINARY} --server \
              --agree-tos --standalone --preferred-challenges http ${LEOPTIONS}

#if [[ ${onlyinsert} != "yes" ]] && md5sum -c "/etc/letsencrypt/live/${MAINDOMAIN}/cert.pem.md5" &>/dev/null; then
if [[ ${onlyinsert} == "yes" ]] && md5sum -c "/etc/letsencrypt/live/${MAINDOMAIN}/cert.pem.md5" &>/dev/null; then
  echo "Cert has not changed, not updating controller."
  exit 0
  echo "Cert has changed or -i option was used, updating controller..."

  # Identrust cross-signed CA cert needed by the java keystore for import.
  # Can get original here:
  cat > "${CATEMPFILE}" <<'_EOF'

  md5sum "/etc/letsencrypt/live/${MAINDOMAIN}/cert.pem" > "/etc/letsencrypt/live/${MAINDOMAIN}/cert.pem.md5"
  echo "Using openssl to prepare certificate..."
  cat "/etc/letsencrypt/live/${MAINDOMAIN}/chain.pem" >> "${CATEMPFILE}"
  openssl pkcs12 -export  -passout pass:aircontrolenterprise \
          -in "/etc/letsencrypt/live/${MAINDOMAIN}/cert.pem" \
          -inkey "/etc/letsencrypt/live/${MAINDOMAIN}/privkey.pem" \
          -out "${TEMPFILE}" -name unifi \
          -CAfile "${CATEMPFILE}" -caname root

  echo "Stopping Unifi and UniFi-Video controllers..."
  systemctl stop unifi unifi-video  

  echo "Removing existing certificate from Unifi protected keystore..."
  keytool -delete -alias unifi -keystore /usr/lib/unifi/data/keystore -deststorepass aircontrolenterprise
  echo "Removing existing certificate from Unifi-Video protected keystore..."
  keytool -delete -alias unifi -keystore /usr/lib/unifi-video/data/keystore -deststorepass ubiquiti
  # following lines are needed for unifi-video
  echo "Inserting certificate into Unifi keystore..."
  keytool -trustcacerts -importkeystore \
          -deststorepass aircontrolenterprise \
          -destkeypass aircontrolenterprise \
          -destkeystore /usr/lib/unifi/data/keystore \
          -srckeystore "${TEMPFILE}" -srcstoretype PKCS12 \
          -srcstorepass aircontrolenterprise \
          -alias unifi

  echo "Inserting certificate into Unifi-Video keystore..."
  keytool -trustcacerts -importkeystore \
          -deststorepass ubiquiti \
          -destkeypass ubiquiti \
          -destkeystore /usr/lib/unifi-video/data/keystore \
          -srckeystore "${TEMPFILE}" -srcstoretype PKCS12 \
          -srcstorepass aircontrolenterprise \

          rm -f "${TEMPFILE}" "${CATEMPFILE}"

  mv /usr/lib/unifi-video/data/ufv-truststore{,.old} # Delete old unifi-video keystore
  sleep 5
  echo "Starting Unifi and UniFi-Video controllers..."
  systemctl start unifi unifi-video 

  echo "Done!"