Execute local bash scripts on remote server but needs user input

7,689

The method you use for remote script execution generates a conflict between code and data flows. I mean... During the execution of ssh user@server 'bash -s' < $script_dir/script.sh, you allocates the standard input (STDIN) for the code that will execute remotely. But if the executed code needs a data input, it will be fed by the next code line (because the STDIN is conveying lines of code to the remote bash process).

If you want to use STDIN to supply input data to a script that runs remotely, you may have to use another stream for the code. OpenSSH seems not to have a native file descriptor forwarding feature yet, that is, STDIN (file descriptor number 0) seems to be the only file descriptor which could be used for data forwarding from the local terminal to the remote session. As a workaround, you could copy the script file in advance, for example:

scp $script_dir/script.sh user@server:/home/user/$script_dir/script.sh && \
ssh user@server /home/user/$script_dir/script.sh

Or you could use Bash hackings in order not to write local code into the remote filesystem. For example:

cat $script_dir/script.sh - | ssh user@server \
bash \<\( head -c `wc -c < $script_dir/script.sh` \)

PS: The hacking above is not optimal because:

  • It does not work if SSH requests authentication data such as user password or key passphrase;

  • The local session requires an additional input line after the end of the remote execution.

Share:
7,689

Related videos on Youtube

Eva Cheung
Author by

Eva Cheung

Updated on September 18, 2022

Comments

  • Eva Cheung
    Eva Cheung almost 2 years

    I am using SSH command to execute the bash scripts remotely:

    ssh user@server 'bash -s' < $script_dir/script.sh
    

    And inside the script.sh, I will have the command like below to add ssh keys:

    ssh-keygen -t rsa
    ssh-copy-id postgres@$sqlserver
    ssh postgres@$sqlserver -C true
    

    And also create user in remote sql server

    printf "Creating user in postgresql server...\n"
    createuser -s -P username
    

    Which need user's input, but I found when I execute the command from the remote server, it will skip getting the users' input and failed.

    Another one is:

    printf "Please enter your barman server name: \n" ; read -s barmanserver
    

    Which cannot read user's input neither

    I know that the script seems cannot read the other terminal's input, but can anyone help me find a solution if I need the user input to continue?

    Thanks a lot!!

    Eva