简体   繁体   中英

How to run commands on remote machine using bash script?

I am trying to run the below commands on remote machine, but nothing is being getting executed, Can anyone point out the issue with the below script?

FYI settings.yml and fuscation_util.rb files are present in the testuser account

SCRIPT:

sshpass -p "PASSWORD" ssh -o StrictHostKeyChecking=no -T root@HOSTNAME <<EOF
    su - testuser
    NEWLINE=$'\n'
    read -s -p "Enter Presto Password:${NEWLINE}" VD_PASSWORD
    KEY=`cat settings.yml |grep '^key:'|sed 's/^key: //'`
    VALUE=`ruby fuscation_util.rb encrypt  "$KEY" "$VD_PASSWORD"`
    echo "$VALUE"
EOF

OUTPUT:

cat: settings.yml: No such file or directory
ruby: No such file or directory -- fuscation_util.rb (LoadError)

I am facing the error only when I try to assign the poutput to some variable, with the below script I didnt get any errors

SCRIPT:

sshpass -p "PASSWORD" ssh -o StrictHostKeyChecking=no -T root@HOSTNAME <<EOF
    su - testuser
    NEWLINE=$'\n'
    read -s -p "Enter Presto Password:${NEWLINE}" VD_PASSWORD
    cat settings.yml |grep '^key:'|sed 's/^key: //'
    ruby fuscation_util.rb encrypt  "testvalue" "testpassword"
EOF

OUTPUT:

WORKING FINE

I believe that because you are connecting as root, the directory you land in when connecting is the root user home directory. Even though you change users, you would still be in the same starting folder (probably /root ).

If you explicitly cd into the desired location before executing the commands, you'll have access to the desired files.

Another option ( suggested by Shravan40 ) would be to specify absolute paths to the files you wish to handle.


It should be mentioned also that allowing root access via SSH is considered a security risk. I would suggest avoiding that if at all possible.

As soon as your ssh connect to the remote host as root it goes to the root directory. So try a change directory inside or give absolute path to the files.

Buts its a security risk though to run commands remotely. Probably you can place a script on the remote host and pass parameter, rather using an echo inside ssh.

Update:

Just make all the assignments before the ssh and use key value as expressions while calling ruby.

Try this:

read -s -p "Enter Presto Password:${NEWLINE}" VD_PASSWORD
sshpass -p "PASSWORD" ssh -o StrictHostKeyChecking=no -T root@HOSTNAME <<EOF
su - testuser
cat settings.yml |grep '^key:'|sed 's/^key: //'
ruby fuscation_util.rb encrypt  `cat settings.yml|grep '^key:'|sed 's/^key: //'` $VD_PASSWORD
EOF

除了使用完整路径之外,您还需要用<<'EOF'替换<<EOF或所有后向滴答声,否则它们将被发送到远程端之前在调用方进行处理。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM