BASH script: Get username or domain given one or the other
So I've been trying to script a bit to make my life easier. One of the things I'm always having to do in my scripts is get the username and domain name. But I'm trying to simplify my life, so I've been working on a bash script part that checks for command-line arguments for username and/or main domain or prompts the user if none are found; but basically tries to make it as automatic as possible.
And as I was typing this, I realized I need to add a check to make sure /home/$username/public_html exists as a sanity check. And figure out the best sanity check to make sure the domain is the main domain.
Anyway, suggestions/upgrades/feedback is welcome. I'm not an expert coder, but I've cobbled this together. What do you think? If it's useful, do let me know - but even more importantly, if you have improvements, PLEASE share so we can help each other be better :)
#!/bin/bash
echo "_________________________________________________________"
echo "Get username/domain:"
# Check to see how many command-line arguments we got
if [ $# -gt 2 ]; then
echo
echo "Too many arguments. Expected 0-2, got: ${#}"
echo
exit;
# If we got two arguments, probably one is the domain and the other is the username.
elif [ $# = 2 ]; then
# If $1 has a dot, it's the domain
if [[ $1 = *'.'* ]]; then
domain="$1";
username="$2";
# if $2 has a dot, it's the domain
elif [[ $2 = *'.'* ]]; then
domain="$2";
username="$1";
# If neither has a dot, abort
else
echo
echo "No viable domain found in arguments."
echo
exit;
fi
elif [ $# = 1 ]; then
# If the argument has a dot, assume it's a domain
if [[ $1 = *'.'* ]]; then
domain="$1";
userfile=$(grep -l "DNS=${domain}" /var/cpanel/users/*)
username=$(cut -d/ -f5 <<<"${userfile}")
# if the argument has no dot, assume it's a username
else
username="$1";
domain=$(cat /var/cpanel/users/${username} | grep ^DNS= | sed s/^DNS=//g | xargs)
fi
else
# We didn't get any command-line arguments, so prompt the user:
echo
read -p "Username or domain: " rawname
# Did we get a dot? If so, assume it's the domain
if [[ $rawname = *'.'* ]]; then
domain="$rawname";
userfile=$(grep -l ${domain} /var/cpanel/users/*)
username=$(cut -d/ -f5 <<<"${userfile}")
# No dot, assume it's the username
else
username="$rawname";
domain=$(cat /var/cpanel/users/${username} | grep ^DNS= | sed s/^DNS=//g | xargs)
fi
fi
echo "Full Domain: ${domain}"
echo " Username: ${username}"
-
To find the user owner of a particular domain name on the server you can use the cPanel supplied script: /scripts/whoowns %domain% To go the other way and list the domain names that a particular user owns, you could script something with: cat /etc/userdomains | grep ": %username%$" | cut -d : -f 1 0 -
Hello, I've moved this to the Developers forum category. Thanks! 0
Please sign in to leave a comment.
Comments
2 comments