userlogs.sh

It sometimes happens when a user on a directadmin server causes heavy load. When this user only has 1 domain it’s easy to figure out what’s going on. But sometimes there are users with a lot more domains. This script makes it easier to tail all of the sites’ acces logs in one go.

#!/bin/bash

##################################################################
# userlogs.sh v1.0                                               #
# tails the acces logs of all the domains of a given user. Makes #
# it a lot easier when 1 user is causing heavy load.             #
# (c)opyleft Take13                                              #
##################################################################

if [ -z "$1" ]
then
        echo "Usage: "$0 "username"
        exit;
fi

cd /home/$1/domains
tail -f `ls -1 | awk '{print "/var/log/httpd/domains/"$1".log"}'`
Identify php versions per domain per user in directadmin

At times you might want to get a list of which php versions are in use by which domain. There’s a plugin for directadmin for that (https://wavoe.bitbucket.io/phpversionlist/phpversionlist.tar.gz) but you can’t easily export the info to excel, especially when doing multiple servers. This script makes a nice csv.

Changelog:
v2.2: 2022/02/11: added creator

#!/bin/bash

##################################################################
# phpversions.sh v2.2                                            #
# Identifies which domain from which user uses which PHP version #
# and exports it to a csv file.                                  #
# Also works with CloudLinux servers and lsphp                   #
# (c)opyleft Take13                                              #
##################################################################
OPTIONSCONF=/usr/local/directadmin/custombuild/options.conf
USERS=/usr/local/directadmin/data/users
OUTFILE=`hostname`.csv
php1=`grep php1_release $OPTIONSCONF | awk -F = '{print $2}'`
php2=`grep php2_release $OPTIONSCONF | awk -F = '{print $2}'`
php3=`grep php3_release $OPTIONSCONF | awk -F = '{print $2}'`
php4=`grep php4_release $OPTIONSCONF | awk -F = '{print $2}'`

#echo "PHP1:" $php1
#echo "PHP2:" $php2
#echo "PHP3:" $php3
#echo "PHP4:" $php4

echo "User;Creator;Domain;PHP" > $OUTFILE

for USER in `ls -1 $USERS` ; do

	CREATOR=`grep creator /usr/local/directadmin/data/users/$USER/user.conf | awk -F = '{print $2}'`
	for DOMAIN in `cat $USERS/$USER/domains.list` ; do

		PHPSELECT=`grep php1_select $USERS/$USER/domains/$DOMAIN.conf | awk -F = '{print $2}'`

		case $PHPSELECT in

			1)
			PHPVER=$php
			;;
			2)
			PHPVER=$php2
			;;
			3)
			PHPVER=$php3
			;;
			4)
			PHPVER=$php4
			;;

			*)
			COUNT=`grep -c php=OFF $USERS/$USER/domains/$DOMAIN.conf`
			if [ "$COUNT" = "1" ] ; then
				PHPVER="PHP uitgeschakeld in domeinconfig"
			else
				PHPVER="Onbekende PHP instelling"
			fi
			;;

		esac

		echo $USER";"$CREATOR";"$DOMAIN";"$PHPVER >> $OUTFILE
		done
	done

If you have multiple servers and want to run it on those servers easily, just make sure you can connect to all servers (via ssh-key) and use this script:

#!/bin/bash

##################################################################
# Distributes phpversions.sh to configured servers, executes the #
# scripts and retrieves the csv file to current directory        #
##################################################################

for HOST in server1 server2 server3 server4 server5 etc ; do

	echo "Sending latest phpversions.sh to "$HOST
	scp phpversions.sh $HOST:
	echo "Gathering info"
	ssh $HOST 'chmod u+x phpversions.sh ; ./phpversions.sh'
	echo "Retrieving info"
	scp $HOST:*.csv .

done
directadmin’s dnssec made easier

Directadmin offers support for DNSSEC. In order to config this you have to edit the zone file, twice. You first to to dns management, search for the domain and click the generate keys button. Then you have to go back and clik the sign button.

You can use the script /usr/local/directadmin/scripts/dnssec.sh but you have to run that twice, first to generate, second to sign. And then you still have to search for the keys in the ksk and vsk files. This script makes that less cumbersome.

#!/bin/bash

SCRIPTPATH=/usr/local/directadmin/scripts
ZONEPATH=/var/named

if [ -z "$1" ]
then
        echo "Usage: "$0" domain"
        exit
fi

DOMAIN=$1
$SCRIPTPATH/dnssec.sh keygen $DOMAIN
$SCRIPTPATH/dnssec.sh sign $DOMAIN

SEC256=`cat $ZONEPATH/$DOMAIN.zsk.key`
SEC257=`cat $ZONEPATH/$DOMAIN.ksk.key`


echo 'Flag 256 (ZSK)'
echo 'Algorithm (RSA/SHA-256)'
echo 'Key: ' $SEC256

echo 'Flag 257 (KSK)'
echo 'Algorithm (RSA/SHA-256)'
echo 'Key: ' $SEC257
A simple watchdog script

At times you find some daemons just stop but since they’re not actively used all the time etc you don’t find out until long after. This script watches the named process. Run it from cron to run checks occasionally (like */15 * * * * for every 15 minutes).

If you replace the

DAEMON=<daemon name>

with

DAEMON=$1

You can run the daemon name as parameter and use this script to check multiple daemons.

#!/bin/bash
# Check for the status of a daemon (with systemd)
# Can be altered to accept daemon's name as command line option
###
# (c)opyleft Take13

# Set your mail address and the name of the process to watch (.service postfix is not necessary).
MAILTO=invaderzim@take13.net
# Example is set to check ntpd. Comment this line and uncomment next to 
# use command line option for daemon name
DAEMON=ntpd
#DAEMON=$1

# No need to edit
STATUS=`/usr/bin/systemctl status $DAEMON | grep Active | awk '{print $2}'`
PID=`/usr/bin/systemctl status $DAEMON | grep 'Main PID' | awk '{print $3}'`
SINCE=`/usr/bin/systemctl status $DAEMON | grep Active | cut -b 19-`
SUBJECT=""

mail_error () {
	( echo "Subject: "$SUBJECT ; echo $STATUS" since "$SINCE ) | sendmail $MAILTO
	}


case $STATUS in
	active) echo "All is well. PID=$PID"
		exit
		;;
	inactive)	echo "Stopped. Restarting "$DAEMON"."
#		/usr/bin/systemctl start $DAEMON
		SUBJECT=$DAEMON" stopped on "`hostname`"."
		mail_error
		;;
	failed)	echo "Failed since "$SINCE
		echo "Restarting"
#		/usr/bin/systemctl restart $DAEMON
		SUBJECT=$DAEMON" failed on "`hostname`"."
		mail_error
		;;
esac
Bad bots (nginx)

Fed up with bots hammering your site? Block them by simply dropping the connection. When they present their user agent all they get is a HTTP 444 (just close connection, do not reply).

if ($http_user_agent ~* (360Spider|80legs.com|Abonti|AcoonBot|Acunetix|adbeat_bot|AddThis.com|adidxbot|ADmantX|AhrefsBot|AngloINFO|Antelope|Applebot|BaiduSpider|BeetleBot|billigerbot|binlar|bitlybot|BlackWidow|BLP_bbot|BoardReader|Bolt\ 0|BOT\ for\ JCE|Bot\ mailto\:craftbot@yahoo\.com|casper|CazoodleBot|CCBot|checkprivacy|ChinaClaw|chromeframe|Clerkbot|Cliqzbot|clshttp|CommonCrawler|comodo|CPython|crawler4j|Crawlera|CRAZYWEBCRAWLER|Curious|Curl|Custo|CWS_proxy|Default\ Browser\ 0|diavol|DigExt|Digincore|DIIbot|discobot|DISCo|DoCoMo|DotBot|Download\ Demon|DTS.Agent|EasouSpider|eCatch|ecxi|EirGrabber|Elmer|EmailCollector|EmailSiphon|EmailWolf|Exabot|ExaleadCloudView|ExpertSearchSpider|ExpertSearch|Express\ WebPictures|ExtractorPro|extract|EyeNetIE|Ezooms|F2S|FastSeek|feedfinder|FeedlyBot|FHscan|finbot|Flamingo_SearchEngine|FlappyBot|FlashGet|flicky|Flipboard|g00g1e|Genieo|genieo|GetRight|GetWeb\!|GigablastOpenSource|GozaikBot|Go\!Zilla|Go\-Ahead\-Got\-It|GrabNet|grab|Grafula|GrapeshotCrawler|GTB5|GT\:\:WWW|Guzzle|harvest|heritrix|HMView|HomePageBot|HTTP\:\:Lite|HTTrack|HubSpot|ia_archiver|icarus6|IDBot|id\-search|IlseBot|Image\ Stripper|Image\ Sucker|Indigonet|Indy\ Library|integromedb|InterGET|InternetSeer\.com|Internet\ Ninja|IRLbot|ISC\ Systems\ iRc\ Search\ 2\.1|jakarta|Java|JetCar|JobdiggerSpider|JOC\ Web\ Spider|Jooblebot|kanagawa|KINGSpider|kmccrew|larbin|LeechFTP|libwww|Lingewoud|LinkChecker|linkdexbot|LinksCrawler|LinksManager\.com_bot|linkwalker|LinqiaRSSBot|LivelapBot|ltx71|LubbersBot|lwp\-trivial|Mail.RU_Bot|masscan|Mass\ Downloader|maverick|Maxthon$|Mediatoolkitbot|MegaIndex|MegaIndex|megaindex|MFC_Tear_Sample|Microsoft\ URL\ Control|microsoft\.url|MIDown\ tool|miner|Missigua\ Locator|Mister\ PiX|mj12bot|Mozilla.*Indy|Mozilla.*NEWT|MSFrontPage|msnbot|Navroad|NearSite|NetAnts|netEstate|NetSpider|NetZIP|Net\ Vampire|NextGenSearchBot|nutch|Octopus|Offline\ Explorer|Offline\ Navigator|OpenindexSpider|OpenWebSpider|OrangeBot|Owlin|PageGrabber|PagesInventory|panopta|panscient\.com|Papa\ Foto|pavuk|pcBrowser|PECL\:\:HTTP|PeoplePal|Photon|PHPCrawl|planetwork|PleaseCrawl|PNAMAIN.EXE|PodcastPartyBot|prijsbest|proximic|psbot|purebot|pycurl|QuerySeekerSpider|R6_CommentReader|R6_FeedFetcher|RealDownload|ReGet|Riddler|Rippers\ 0|rogerbot|RSSingBot|rv\:1.9.1|RyzeCrawler|SafeSearch|SBIder|Scrapy|Scrapy|Screaming|SeaMonkey$|search.goo.ne.jp|SearchmetricsBot|search_robot|SemrushBot|Semrush|SentiBot|SEOkicks|SeznamBot|ShowyouBot|SightupBot|SISTRIX|sitecheck\.internetseer\.com|siteexplorer.info|SiteSnagger|skygrid|Slackbot|Slurp|SmartDownload|Snoopy|Sogou|Sosospider|spaumbot|Steeler|sucker|SuperBot|Superfeedr|SuperHTTP|SurdotlyBot|Surfbot|tAkeOut|Teleport\ Pro|TinEye-bot|TinEye|Toata\ dragostea\ mea\ pentru\ diavola|Toplistbot|trendictionbot|TurnitinBot|turnit|Twitterbot|URI\:\:Fetch|urllib|Vagabondo|Vagabondo|vikspider|VoidEYE|VoilaBot|WBSearchBot|webalta|WebAuto|WebBandit|WebCollage|WebCopier|WebFetch|WebGo\ IS|WebLeacher|WebReaper|WebSauger|Website\ eXtractor|Website\ Quester|WebStripper|WebWhacker|WebZIP|Web\ Image\ Collector|Web\ Sucker|Wells\ Search\ II|WEP\ Search|WeSEE|Wget|Widow|WinInet|woobot|woopingbot|worldwebheritage.org|Wotbox|WPScan|WWWOFFLE|WWW\-Mechanize|Xaldon\ WebSpider|XoviBot|yacybot|Yahoo|YandexBot|Yandex|YisouSpider|zermelo|Zeus|zh-CN|ZmEu|ZumBot|ZyBorg) ) {
    return 444;
}
Convert files to webp

Do you have a folder with many images that you want to convert to webp? Don’t want to do it all by hand? Use this script then. You will need to set the WORKDIR variable, and perhaps change the path to the bash shell (like when you’re on FreeBSD, the path is /usr/local/bin/bash).

Requirements: webp (obviously, see https://developers.google.com/speed/webp/download), bash (duh), basename (should be installed already).

#!/bin/bash

WORKDIR=/path/to/images

# Search for files per extension in subdirectories and convert them to webp.
for EXT in jpg jpeg JPG JPEG ; do

        for DIR in `find $WORKDIR -type d` ; do

                for FILE in `ls -1 $DIR/*.$EXT` ; do
                        FILENAME=`basename --suffix=.$EXT $FILE`
                        /usr/bin/cwebp $FILE -o $DIR/$FILENAME.webp
                done

        done

done
repair and optimize all tables

Sometimes the database daemon crashes (because the server ran out of swap space for example). This can cause the databases to be damaged. Finding and repairing the database table in question can be an arduous task, especially if you have a lot of databases. This script runs both repair and optimize on all tables.

You’ll first need a .my.cnf file in your own directory (/root/.my.cnf if you’re root for example), with the following contents:

[client]
user=YOURUSERNAMEHERE
password=YOURPASSWORDHERE

For instance, if you’re running directadmin, they username is da_admin. The password can be found in /usr/local/directadmin/conf/mysql.conf

This script does work for all situations of MySQL and MariaDB though, so do not get hung up on the username. Just use the username you need to access ALL the databases. Make sure the permissions on the file are 600.

Here’s the (simple) script:

# Finding and repairing the database table in question can be an
# arduous task, especially if you have a lot of databases. This
# script runs both repair and optimize on all tables.
###
# (c)opyleft Take13
#!/bin/bash

MYSQLBIN=/usr/bin/mysql

for DATABASE in `echo "show databases" | $MYSQLBIN | grep -v Database | grep -v information_schema | grep -v performance_schema` ; do
        for TABLE in `echo "show tables" | $MYSQLBIN $DATABASE | grep -v Tables_in_` ; do
                echo $DATABASE"."$TABLE
                echo "repair table "$DATABASE"."$TABLE | $MYSQLBIN
                echo "optimize table "$DATABASE"."$TABLE | $MYSQLBIN
        done
done
Automatically block asshole bots

There’s a great many bots out there that set off so many requests webservers can get swamped. This script searches for particular user agents, finds the originating ip address (ipv4 or ipv6) and then blocks the whole subnet. This is specifically done for yandex and MJ12bot who use a large amount of subnets.

This script uses directadmin’s ConfigServer Security & Firewall (csf) which needs to be installed seperately.

# This script searches for particular user agents, finds the 
# originating ip address (ipv4 or ipv6) and then blocks the whole 
# subnet. This is specifically done for yandex and MJ12bot who use a
# large amount of subnets.
###
# (c)opyleft Take13
#!/bin/bash

# Variables
BADBOTS=adscanner\|AhrefsBot\|Baiduspider\|BLEXBot\|DotBot\|Exabot\|OpenindexSpider\|Pinterestbot\|Seekport\|SeznamBot\|YandexBot\|YandexImages\|MJ12Bot\|ltx71\|Baiduspider\|Qwantify\|OpenindexSpider
LOGPATH=/var/log/httpd/domains/
LOGS=`ls -1 $LOGPATH/*log | grep -v error | grep -v bytes`

# Comment to keep the logfile of blocked ip addresses/net blocks
rm /root/blocked.txt

# Find badbots in logfile and block with iptables
echo "Searching for bad bots in $LOG."

for LOG in `echo $LOGS` ; do
        # This line searches for ip addresses, remove comment to use, make sure the next for statement is commented out
        #for IP in `egrep $BADBOTS $LOG | awk '{print $1}' | awk '{print $1}' | sort | uniq` ; do

        # This line searches for net blocks, remove comment to use, make sure the previous for statement is commented out
        for IP in `egrep -i $BADBOTS $LOG | awk '{print $1}' | sort | uniq | awk '{print "whois -l "$1" | grep route | grep -v mnt"}' | sh | awk '{print $2}' | sort | uniq` ; do

                echo $IP
                echo $IP >> /root/blocked.txt
                csf -d $IP

        done

done
Restart all daemons

Sometimes a (directadmin) server runs out of swap space. It’s nice to know which service exactly is causing it but sometimes you do not have the time. A fast option to restart all services without having to figure out exactly which services you’ve got running (especially now that there’s the possibility of using 4 different versions of PHP).

#!/bin/bash

# Specifically for directadmin/custombuild and CentOS
# Detects (some) options and restarts daemons, then
# shows free swap space
###
# (c)opyleft Take13

OPTIONS=/usr/local/directadmin/custombuild/options.conf 

# Show free swap space
function swapfree {
	echo Swap free: `free -h | grep Swap | awk '{print $4}'`
	}

# Detect running php-fpm instances, restart
for PHP in `systemctl | grep php-fpm | awk -F . '{print $1}'`; do
	echo Restarting $PHP
        systemctl restart $PHP
	swapfree
done

# Detect webserver config, restart
WEBSERVER=`grep webserver $OPTIONS | awk -F = '{print $2}'`

case $WEBSERVER in
apache)		echo Restart apache
		systemctl restart httpd
		swapfree
;;
nginx)		echo Restart nginx
		systemctl restart nginx
		swapfree
;;
nginx_apache)	echo Restart nginx
		systemctl restart nginx
		swapfree
		echo Restart apache
		systemctl restart httpd
		swapfree
;;
litespeed)	echo Restart litespeed
		systemctl restart lsws
		swapfree
;;
esac

# Restart exim
echo "Restart exim"
systemctl restart exim
swapfree

# Restart dovecot
echo "Restart dovecot"
systemctl restart dovecot
swapfree

# Detect database, restart
DB=`grep inst $OPTIONS | awk -F = '{print $2}'`
case $DB in
mysql)		echo Restart MySQL
		systemctl restart mysqld
		swapfree
;;
mariadb)	echo Restart MariaDB
		systemctl restart mariadb
		swapfree
;;
esac

echo "*kusje*"