I do not know that this is a duplicate question. I have, as I always do, research until I do not have a workable solution or have not figured it out by myself. I am not frivolous. I can split this string at the delimiter in minutes. That is not why I am here. I am security conscious. This is user input from command line input. I am trying to verify and validate user input and I do not consider that a wasted effort. I'm doing something fairly simple, however my level of expertise can't figure this out. I am taking a command line option input from a script and it goes into three variables.
$LOCAL_FILE
$DESTINATION_USER
$DESTINATION_FILE
I'll be using scp and /etc/hosts to verify before processing.
I take $DESTINATION_USER
which is example: user@xu4-node1-2 and run the user thru my not working regex (Which I use elsewhere in an if conditional and it works fine); to verify format and remove the "user@" part so that I can awk /etc/hosts to get the IP of the user so that I can verify and put the hostname and ip into an associative array (That is used for a similar reason).
sUSER=$DESTINATION_USER
[[ "$sUSER" =~ "([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])(\.([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9]))*$" ]]
ip=$(awk '/^[[:space:]]*($|#)/{next}/'$sUSER'/{print $1; exit}' /etc/hosts)
declare -A dUSER[$ip]=$sUSER
For example, I need to verify user input "user@xu4-node1-2" and loose the "user@" part so all I have is "xu4-node1-2" so I can give it to the awk to give me the ip. My regex however gives me the whole "user@xu4-node1-2"
I use the regex in this:
elif [[ $i =~ ^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])(\.([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9]))* ]]; then
and it works fine.
** Update
I was able to complete this code to resolve my problem. I am posting it here in case it can help anyone else. I included verification and validation of user input, un-tainting it and though it's not in this snippet, input from the hosts file as well. I also included some error handling.
sUSER=$DESTINATION_USER
sUSER="${sUSER#"${sUSER%%[![:space:]A-Za-z0-9._%+-]*}@"}"
if [[ $sUSER =~ ^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])(\.([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9]))*$ ]]; then
ip=$(awk '/^[[:space:]]*($|#)/{next}/'$sUSER'/{print $1; exit}' /etc/hosts)
if ! [[ $ip ]]; then
printf "\n${LtRED} --> Error - No reference IP address found in /etc/hosts file for $sUSER\n --> Make sure that your hosts file is properly formatted${RESET}\n\n"
exit 1
fi
declare -A dUSER[$ip]=$sUSER
else
printf "\n${LtRED} --> Remote user address ( $sUSER ) is not formatted properly - Try Again${RESET}\n\n"
exit 1
fi