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 ping.sh file and then

chmod +x ping.sh

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

sh ping.sh 192.168.1.

#!/bin/sh
# simple ping scan utility

# i.e. 192.168.0.
ipFirstPart=$1

ip=0
while [ $ip -ne 255 ] 
do 
  ip=$(($ip+1))
  ping -w1 $ipFirstPart${ip} | grep "64 bytes from"
done

LibreNMS backup script

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

#!/bin/bash

# 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 teams.sh script, you can trigger a backup notification
ALERT="/home/admin/teams.sh -b"

# Directory to backup to
bDir="/backup"
bName="librenms_backup"

# MySQL settings for tar and sqldump
sqlDir="/var/lib/mysql"
sqlDB="librenms"
sqlUN="root"
sqlPW=""
LOG="${bDir}/${lDate}-${bName}.log"

# Directory that contains data
dDir="/opt/librenms"

# 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"
else
        echo "backup dir not available.  Quiting"
        exit 1
fi

${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}"
else
        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}"
fi

# MySQL data backup
tar -zcvf ${bDir}/${lDate}-${bName}-mysql.tgz ${sqlDir}
if [ $? -eq 0 ]; then
        echo "Tar succesfully backed up ${sqlDir}"
else
        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}"
fi

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"
else
        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"
fi

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

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

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

The following uses the ubntmod.sh 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 192.168.1.1 – 192.168.1.254, 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 ./ubntmod.sh -i ${ip}${i} -e ; else echo ${ip}$i not alive; fi ; done 

Broken out for easier reading.

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

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

192.168.1.1 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 nightlight.sh file

chmod +x nightlight.sh

and run

./nightlight.sh on .5

Code:

#!/bin/sh
export DISPLAY=$(w $(id -un) | awk 'NF > 7 && $2 ~ /tty[0-9]+/ {print $3; exit}')
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games

display=`xrandr | grep "\ connected" | cut -d" " -f1`
brightness="$2"
# Check if brightness was specified.  If not, set screen to 50% brightness
if (echo $2 | grep [0-9]);then
         brightness="$2"
elif (echo $1 | grep -q help);then
         echo "############"
else
         brightness=".5"
         echo "Brightness variable not set, setting to fallback of 50%"
fi
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 sunrise-sunset.com/timezone/time
# 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
./nightmode.sh on/off brightness
Examples: 
Turn nightmode on and set screen brightness to 75%
./nightmode.sh on .75
Turn night mode off and set screen brightness to 100%
./nightmode.sh off 1
"
}
case $1 in
  off) night_mode 1:1:1 1.0 ;;
  help) help ;;
  auto) auto ;;
  *) night_mode 1:1:0.5 ;;
esac

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

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

Bash script to send messages to Microsoft Teams

Copy and save into teams.sh file. Make executable. Change web hook, Run!

The script is a modified Slack script from off the web.

#!/bin/bash
# bash script to send messages to Microsoft Teams.
function usage {
echo "HELP ME!"
echo "description: send messages to Microsoft Teams channels"
echo "special notes: You'll need to change the teamsUrl variable to contain your webhook from Teams."
echo "usage: ${0} -b \"Message contents\""
echo " -m Message body"
echo " -h This help info"
exit 1
}
while getopts "m:h" opt; do
case ${opt} in
m) msgBody="$OPTARG"
;;
h) usage
;;
\?) echo "Invalid option -$OPTARG" >&2
;;
esac
done
# Add/Change the webhook to one you created in Teams
teamsUrl="https://teamswebhook"
if [[ ! "${msgBody}" ]]; then
echo "You didn't specify a message!"
usage
fi
read -d '' payLoad << EOF
{
"text": "${msgBody}",
}
EOF
statusCode=$(curl \
--write-out %{http_code} \
--silent \
--output /dev/null \
-X POST \
-H 'Content-type: application/json' \
--data "${payLoad}" ${teamsUrl})
echo ${statusCode}

Bash script to monitor system service

This bash script runs and checks to see if a service like httpd, or mysql is running and alerts if it is not.

Script Usage

servicemonitor.sh httpd mariadb

Where httpd and mariadb are the services you want to monitor/check.

Setup Script

Create servicemonitor.sh file and paste the following contents in.

#!/bin/bash

timeHour=`date +%H` # date/time just shows the hour
quietHour="02"    # If it is this hour, then exit program, useful if services are expected to go down during a particular time for maintenance
if ( echo ${timeHour} | grep ${quietHour}); then
         echo "Is during quiet time.  Quiting."
         exit
fi

 function ALERT {
 msg="~/teams.sh -b"  # Sends a message to Microsoft Teams channel.  Needs the teams.sh script in the users home directory.
 ${msg} "$1"
 }
 function SERVICECHECK {
 serviceName="${1}"
 if (systemctl status ${serviceName} | grep Active | grep inactive); then
         ALERT "ERROR: $(hostname) - ${serviceName} - ${0} is inactive"
         echo "ERROR: ${serviceName} is inactive!"
 else
         echo "Running!"
 fi
 }
 for i in $@
 do
 echo Checking ${i}
 SERVICECHECK ${i}
 done

Note the teams.sh script that is called is another script that is called that sends an alert to Microsoft Teams. Is not needed for this script to run, but allows for remote alerting.

Save file and make it executable

chmod +x servicemonitor.sh

Add script to crontab (Optional)

crontab -e

The following runs the script every 5 minutes. Can change the 5 to 1 to run every minute. Change httpd and mariadb to the service you want to monitor.

*/5 * * * * /home/UserName/servicemonitor.sh httpd mariadb

BASH Script to add new SFTP user and setup permissions

This script adds a new SFTP user with only sftp access.  Refer to this post on setting up a SFTP server.

Download script

wget www.incredigeek.com/home/downloads/scripts/sftpUserAdd.sh

Make executable

chmod +x sftpUserAdd.sh

Run with the new user you want to create.

./sftpUserAdd.sh sftpUsername

You may need to edit the script and modify the location parameters.

#!/bin/bash
# Automatically setup and add SFTP user
# Script creates new user and setups permissions
newUser=$1
sftpDir="/sftp/"
if grep -q ${newUser} /etc/passwd ;then
echo ${newUser} Already exsists. Aborting!
exit 1
else
mkdir -p ${sftpDir}/${newUser}/files
useradd -g sftpusers -d ${sftpDir}/${newUser}/files -s /sbin/nologin ${newUser}
passwd ${newUser}
chown ${newUser}:sftpusers /sftp/CareMark/files
fi

Zenoss 5 backup Script

#!/bin/bash

# Zenoss 5 backup script
# 
#

# CHANGE THESE VARIABLES 
# Zenoss 5 Backup log file
log="/root/zenbackup.log"
# Backup directory
bdir="/backup/zenbackup/"

echo "Starting Zenoss backup Script"

echo "Starting backup to ${bdir}." $(date) >> ${log}
echo "Starting Backup to ${bdir}." $(date)

# Stop Zenoss Service
serviced service stop Zenoss.core

wait

# Wait for Zenoss to stop and then continue the backup
while [ -ne `serviced service status Zenoss.core | grep Stopped` ]
do
        echo "Waiting for Zenoss to Stop"
        sleep 5
done

# Backup
echo "Starting Zenoss Backup"
serviced backup ${bdir} 
echo "Backup Finished"

wait    

# Start Zenoss
echo "Starting Zenoss"
serviced service start Zenoss.core

echo "Finished backup." $(date) >> ${log}
echo "Finished backup." $(date)

exit