Generate hosts file on a cpanel server quickly

So here’s how to quickly generate a hosts file on a cPanel server, or rather how to print out a bunch of lines of text that can be appended to someone’s local “hosts file”:

#!/bin/bash
# set www="no" if you don't want www to be prepended to each entry.
www="yes" 
cd /var/cpanel/users 2>/dev/null && for userfile in *; do
	echo "#$userfile";
	ip=$(awk -F\= '$1 == "IP" {print $2}' "$userfile")
	domains=
	domain=$(egrep '^DNS([0-9]+)?\=' "$userfile" | awk -F\= '{print $2}')
	if [[ "$www" = "yes" ]]; then
		domain="${domain} www.${domain}"
	fi
	domains+=${domain}
	for domain in ${domains[@]}; do
		echo "$ip $domain"
	done
done || (echo "Error: Is this a cPanel server?"; exit 1) 

Quick one-liner you can paste directly on a server over ssh:

www="yes"; cd /var/cpanel/users 2>/dev/null && for userfile in *; do echo "#$userfile"; ip=$(awk -F\= '$1 == "IP" {print $2}' "$userfile"); domains=; domain=$(egrep '^DNS([0-9]+)?\=' "$userfile" | awk -F\= '{print $2}'); if [[ "$www" = "yes" ]]; then domain="${domain} www.${domain}"; fi; domains+=${domain}; for domain in ${domains[@]}; do echo "$ip $domain"; done; done || (echo "Error: Is this a cPanel server?"; exit 1)

Quick and dirty. Mostly useful if you are a sysadmin for a hosting company that uses cPanel, or you use cPanel and need to generate a “hosts file” quickly for testing a server migration.

I wonder if there is a better way to do this using cPanel’s API? I’ve never bothered looking into it. Might be a fun project for someone out there.

Leave a Reply

Your email address will not be published. Required fields are marked *