Hello,
I had to make an ssh connection to remote server from a bash shell script. I've summarized my research and I want to share it with you. I hope it will be useful to somebody or it will get improved.
Bash has an option, which is called "input redirection", I think. It is something similar to this:
#!/bin/sh
mysql -u tsurko -p mydb <<EOF
SELECT * FROM test_table;
SELECT * FROM other_table;
quit
EOF
exit
This script will connect to MySQL, will run the two queries and will quit. In similar way we can make an ssh connection in bash script. Here is some example code:
#!/bin/sh
ssh example.com <<EOF
touch test_file
exit
EOF
exit
This way you can execute anything you want on the remote server. I have the following errors, while running the script:
Warning: no access to tty (Bad file descriptor).
Thus no job control in this shell.
As far as I know this is known issue and it has been discussed in the forum. I haven't tried to fix it - it works for me.
Here is an example, using shell variables in the script:
#!/bin/sh
TEST_VAR=sample_file
ssh example.com <<EOF
touch $TEST_VAR
exit
EOF
echo "I'm back"
exit
In this case the value of variable TEST_VAR is acquired from the local environment. Ny local I mean the environment, where the script is executed. So on the remote machine we have executed the command "touch sample_file".
Here is another example showing how to use environment variables, declared on the remote server:
#!/bin/sh
TEST_VAR=sample_file
ssh example.com <<EOF
touch \$TEST_VAR
exit
EOF
echo "I'm back"
exit
Let's assume that we have TEST_VAR set on the remote server. We have escaped the $ character in our script, so $TEST_VAR is treated as string, not as a variable. On the remote server we have executed "touch $TEST_VAR". and TEST_VAR's value is acquired from there.
And finally let's assume that we have to run some commands on two or more machines. It's very inconvenient to have them two or more times (for each session). In this case the following workaround can be used. A text file is created and the desired commands are saved there. Then we can use "`cat <filename>`" in the script and they will be executed on the server. :
#!/bin/sh
ssh example.com <<EOF
`cat test.cmd`
exit
EOF
ssh example2.com <<EOF
`cat test.cmd`
exit
EOF
exit
and more convenient solution (thanks to ddreggors):
#!/bin/sh
ssh example1.com `cat test.cmd`
ssh example2.com `cat test.cmd`
Don't forget that the file must contain only commands, written in the way we want them executed on the server. The file can't be a bash script - any variables and so on won't be parsed.
That's it. I'll be glad to hear any suggestions, corrections, critics or just opinions. Corrections about my English are also welcome - it's not my mother tongue.