Links on sending/receiving imessages with applescript or bash

https://apple.stackexchange.com/questions/331468/bash-script-detect-received-imessage-along-with-its-contents

Command line program to send imessage messages
https://github.com/linjunpop/imessage

Chat bot
https://github.com/ZekeSnider/Jared

Run bash commands from Applescript
https://www.cyberciti.biz/faq/mac-osx-applescript-run-shell-script/

Applescript Documentation archive
https://developer.apple.com/library/archive/documentation/AppleScript/Conceptual/AppleScriptLangGuide/introduction/ASLR_intro.html

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 unifi.domain.com

Executing Script to Renew Certificate

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

sudo ./gen-unifi-cert.sh -e email@domain.com -d unifi.domain.com

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

./gen-unifi-cert.sh -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/gen-unifi-cert.sh -r -d unifi.domain.com

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 https://git.sosdg.org/brielle/lets-encrypt-scripts/raw/branch/master/gen-unifi-cert.sh
# More info here https://www.reddit.com/r/Ubiquiti/comments/43v23u/using_letsencrypt_with_the_unifi_controller/ 
# And here https://www.reddit.com/r/Ubiquiti/comments/43v23u/using_letsencrypt_with_the_unifi_controller/
# Modified script from here: https://github.com/FarsetLabs/letsencrypt-helper-scripts/blob/master/letsencrypt-unifi.sh
# Modified by: Brielle Bruns <bruns@2mbit.com>
# Download URL: https://source.sosdg.org/brielle/lets-encrypt-scripts
# 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]gmail.com> 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
#LEBINARY="/usr/src/letsencrypt/certbot-auto"

PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"

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
       exit;;
  esac
done

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
      LEBINARY=${i}
      echo "Found LetsEncrypt/Certbot binary at ${LEBINARY}"
      break
    fi
  done
fi

# 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 get-letsencrypt.sh script to install it"
  exit 1
fi

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

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

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

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

MAINDOMAIN=${domains[0]}

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

if [[ ${renew} == "yes" ]]; then
  LEOPTIONS="${RENEWCERT}"
else
  LEOPTIONS="${email} ${DOMAINS} ${NEWCERT}"
fi

#if [[ ${onlyinsert} != "yes" ]]; then
if [[ ${onlyinsert} == "yes" ]]; then
  echo "Firing up standalone authenticator on TCP port 80 and requesting cert..."
  ${LEBINARY} --server https://acme-v01.api.letsencrypt.org/directory \
              --agree-tos --standalone --preferred-challenges http ${LEOPTIONS}
fi

#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
else
  echo "Cert has changed or -i option was used, updating controller..."
  TEMPFILE=$(mktemp)
  CATEMPFILE=$(mktemp)

  # Identrust cross-signed CA cert needed by the java keystore for import.
  # Can get original here: https://www.identrust.com/certificates/trustid/root-download-x3.html
  cat > "${CATEMPFILE}" <<'_EOF'
-----BEGIN CERTIFICATE-----
MIIDSjCCAjKgAwIBAgIQRK+wgNajJ7qJMDmGLvhAazANBgkqhkiG9w0BAQUFADA/
MSQwIgYDV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CERTIFICATE-----
_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!"
fi

Bash ANSI-C Quoting

Pulled from https://www.gnu.org/software/bash/manual/bashref.html#ANSI_002dC-Quoting

As a side note there is a lot of good bash info out here. https://www.gnu.org/software/bash/manual/bashref.html

3.1.2.4 ANSI-C Quoting

Words of the form $'string' are treated specially. The word expands to string, with backslash-escaped characters replaced as specified by the ANSI C standard. Backslash escape sequences, if present, are decoded as follows: \a

alert (bell) \b

backspace \e\E

an escape character (not ANSI C) \f

form feed \n

newline \r

carriage return \t

horizontal tab \v

vertical tab \\

backslash \'

single quote \"

double quote \?

question mark \nnn

Some examples

echo Hello $'\t' World

Returns “Hello World” with a tab space between both words.

echo Hello $'\n' World

Returns Hello on one line and World on the second

echo "\"Hello World\""

Returns “Hello World” inside double quotes

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

Add multiple IP bindings to Mikrotik Hotspot – Bash Script

Copy and paste the following into a file named mtbypass.sh and then “chmod +x mtbypass.sh”  Or download from this direct link.  Be sure to change the username and password

#!bin/bash
filelist="bypasslist.txt"
username="admin"
password="password!"
ip="$1"

for i in `cat ${filelist}`
do
address=`echo $i | cut -d= -f1`
mac=`echo $i | cut -d= -f2`
sshpass -p ${password} ssh ${username}@${ip} "ip hotspot ip-binding add address=${address} mac-address=${mac} type=bypassed"
done

Now create a file named bypasslist.txt and put all the addresses you want bypassed.  You’ll need the Mac Address and the IP Address.

Example file

192.168.88.2=4C:5E:0C:B8:4E:01
192.168.88.3=3E:AA:A1:2D:8B:2C
192.168.88.5=DE:D1:39:65:91:4E

Usage of script is

./mtbypass.sh MikrotikIP

Example:

./mtbypass.sh 192.168.88.1

Upload ssh key to multiple servers automatically

Here is a quick script I created to automate copying a ssh key to multiple remote servers.

Basic command – the command uses sshpass to upload the ssh key to a remote server, this allows you to execute the command and not have to enter in a password to authenticate.

sshpass -p password ssh-copy-id -o StrictHostKeyChecking=no admin@remotehost

Script

#!/bin/bash

remotehosts="$1"
username="admin"
password="MyCoolPassword123"

for host in `cat ${remotehosts}`
do
sshpass -p${password} ssh-copy-id -o StrictHostKeyChecking=no ${username}@${host}
echo "Uploaded key to " ${host}
done

echo "Finished!"

 

Using the script

  1. Download here.
  2. Make it executable
    chmod +x sshcopy.sh
    
  3. Edit the script and change the username and password.
  4. Create a file that contains each host’s IP address or hostname.
  5. Run script (change hostlist.txt to your host list you created in step 3.)
    ./sshcopy.sh hostlist.txt
  6. Wait for the script to finish.

Example:

wget www.incredigeek.com/home/downloads/SSHCopy/sshcopy.sh
chmod +x sshcopy.sh
sed -i s/admin/bob/g sshcopy.sh                      <-- Change username - you can just manually edit the file,
sed -i s/MyCoolPassword123/password/g sshcopy.sh     <-- Change password - it might be easier than using sed
echo "192.168.1.100" >> host.txt                     <-- Add 192.168.1.100 to the host list
echo "Bob" >> host.txt                               <-- Add hostname bob to host list
./sshcopy.sh host.txt                                <-- Upload ssh key to all host's in the host file i.e. "bob" and "192.168.1.100"