Run yes/no script remotely

I have this script in server2

[root@server2 ~]# cat /root/yesno.sh
#!/bin/bash

read -p "are you sure?" -n 1 -r

if [[ $REPLY =~ ^[Yy]$ ]]; then
        echo ""
        echo "YES"
else
        echo "NO"
fi


[root@server2 ~]# sh  /root/yesno.sh
are you sure?y
YES

It works fine. I have installed ssh keys between server1 and server2. When I run the script from server1 as follows, it does not prompt the question. However, if I press Y, it gives correct output. How can I get the question printed into the shell?

[root@server 1~]# ssh root@11.22.33.44   sh  /root/yesno.sh
y

YES

You are using bash features, but running it in sh.

To run it in bash, use bash.

There's a shebang #!/bin/bash in the script, but running it with
sh scriptname bypasses the shebang's effect. The reote script needs to be executable. And run that way.

# one time only
ssh root@11.22.33.44 ' chmod +x /root/yesno.sh'

ssh root@11.22.33.44 ' /root/yesno.sh'

Also try to keep the remote command surrounded by ' or by " or you will get unexpected results - in general. See the examples above.

PS: root access by ssh is usually a bad idea. If this is a home network, maybe. For business, no. Would not pass a reasonable security audit.

I have modified to /bin/sh and changed script to 755. Still same result. I am using ssh keys between servers.

# cat /root/yesno.sh
#!/bin/sh


-rwxr-xr-x 1 root root 116 Feb 20 05:17 /root/yesno.sh


#  ssh root@IP /root/yesno.sh
y

YES


#  ssh root@IP   '/root/yesno.sh'
y

YES


# ssh root@IP  "/root/yesno.sh"
y

YES

Try

ssh -t root@10.1.1.3 ./yesno.sh
are you sure?

Before, the problem was that you were accidentally running it in sh when you should have been using bash.

Now, you are intentionally running it in sh when you should be using bash.

If you want bash features like read -p, use bash!

2 Likes