Failed to add a string to a file on a remote host

40 views Asked by At

I've written function to execute any command on a remote host.

## The ssh connection function
ssh_function(){
    local IP="$1"
    local COMMAND="$2"
    local STATUS

    if [[ $IP == $(hostname -i) ]]
    then
        STATUS=$(${COMMAND} 2>/dev/null)
    else
        STATUS=$(ssh -o "StrictHostKeyChecking no" -i $KEY_PATH root@"$IP" ${COMMAND} 2>/dev/null) 
    fi

    echo "$STATUS"
}

So if $IP is an local IP address the command will be executed on a localhost.

When I try to add these commands in the script:

ssh_function $CURRENT_NODE_IP "echo 'LimitMEMLOCK=infinity' >> /usr/lib/systemd/system/opensearch.service"

ssh_function $CURRENT_NODE_IP "echo 'MAX_LOCKED_MEMORY=unlimited' >> /usr/lib/systemd/system/opensearch.service"

I see in terminal

'LimitMEMLOCK=infinity' >> /usr/lib/systemd/system/opensearch.service
'MAX_LOCKED_MEMORY=unlimited' >> /usr/lib/systemd/system/opensearch.service

So the ssh_function prints them in terminal and doesn't add them to the file.

Therefore if the parameter $2 has >> or '' or "", the function works as echo operator.

The same situation with command

ssh_function $CURRENT_NODE_IP "sed -i 's/^-Xms.*/-Xms2g/' /etc/opensearch/jvm.options"

But that command

ssh_function $CURRENT_NODE_IP "apt -qq install opensearch=1.3.12"

works perfectly.

I can't understand the logic. Should I screen the "" symbols in the argument $2 ($COMMAND)?

PS1. After @tjm3772 comment I've edited the function

ssh_function3(){
    local IP="$1"
    local OPTION="$2"
    local FILE="$3"

    if [[ $IP == $(hostname -i) ]]
    then
        echo $OPTION >> $FILE
    else
        ssh -o "StrictHostKeyChecking no" -i $KEY_PATH root@"$IP" echo $OPTION >> $FILE
    fi
}

It works, but only for the >> operator.

PS2. The answer

I just use the eval operator in the function

## The ssh connection function
ssh_function(){
    local IP="$1"
    local COMMAND="$2"

    if [[ $IP == $(hostname -i) ]]
    then
        eval "${COMMAND} 2>/dev/null"
    else
        eval "ssh -o "StrictHostKeyChecking no" -i $KEY_PATH root@"$IP" ${COMMAND} 2>/dev/null"
    fi
}
0

There are 0 answers