refactor: Improve script maintainability and readability with cleaner functions
This commit is contained in:
parent
31c8af3446
commit
ad59ebcf3a
1 changed files with 22 additions and 18 deletions
|
@ -16,40 +16,44 @@ parse_ssh_port() {
|
|||
echo $port
|
||||
}
|
||||
|
||||
search_ssh_user() {
|
||||
parse_ssh_config() {
|
||||
for ssh_config in `awk '
|
||||
$2 == "Host" {
|
||||
gsub("\\\\.", "\\\\.", $3);
|
||||
gsub("\\\\*", ".*", $3);
|
||||
host = $3;
|
||||
$1 == "Host" {
|
||||
gsub("\\\\.", "\\\\.", $2);
|
||||
gsub("\\\\*", ".*", $2);
|
||||
host = $2;
|
||||
next;
|
||||
}
|
||||
$2 == "User" {
|
||||
$2 = "";
|
||||
$1 == "User" {
|
||||
$1 = "";
|
||||
sub( /^[[:space:]]*/, "" );
|
||||
printf "%s|%s\n", host, $0;
|
||||
}' $1`; do
|
||||
local host_regex=${ssh_config%|*}
|
||||
local host_user=${ssh_config#*|}
|
||||
if [[ "$2" =~ $host_regex ]]; then
|
||||
ssh_user=$host_user
|
||||
if [[ "$2" == $host_regex ]]; then
|
||||
ssh_user_found=$host_user
|
||||
break
|
||||
fi
|
||||
done
|
||||
|
||||
echo $ssh_user
|
||||
echo $ssh_user_found
|
||||
}
|
||||
|
||||
get_ssh_user() {
|
||||
# Set default ssh_user as current user
|
||||
local ssh_user=$(whoami)
|
||||
|
||||
# Search SSH User information in global configuration file
|
||||
ssh_user=$(search_ssh_user /etc/ssh/ssh_config $1)
|
||||
|
||||
# Search SSH User in user local file if available
|
||||
if [ -f ~/.ssh/config ]; then
|
||||
# Search SSH User information in user configuration file
|
||||
ssh_user=$(search_ssh_user ~/.ssh/config $1)
|
||||
ssh_user=$(parse_ssh_config ~/.ssh/config $1)
|
||||
fi
|
||||
|
||||
# If SSH User not found, search in global config file
|
||||
if [ -z $ssh_user ]; then
|
||||
ssh_user=$(parse_ssh_config /etc/ssh/ssh_config $1)
|
||||
fi
|
||||
|
||||
#If SSH User not found in any config file, return current user
|
||||
if [ -z $ssh_user ]; then
|
||||
ssh_user=$(whoami)
|
||||
fi
|
||||
|
||||
echo $ssh_user
|
||||
|
|
Loading…
Reference in a new issue