I have a backup sync program on local server. I have an ssh password less login set up, and I can run commands on an external server in bash script doing:
ssh [email protected] "sync; sync; /sbin/shutdown -h now"
How do I run multiple commands in bash on a remote Unix or Linux server? What is the best way to SSH in and run various unix commands in a bash shell?
[donotprint][/donotprint]There are various ways to run multiple commands on a remote Unix server. The syntax is as follows.
Simple bash syntax to run multiple commands on remote machine
Simply run command2 if command1 successful on a remote host called foo:
$ ssh [email protected] "command1 && command2"
How To Run Multiple SSH Command
Run date and hostname commands:
$ ssh [email protected] "date && hostname"
You can run sudo command as follows on a remote box called server1.sxi.io:
$ ssh -t [email protected] "sudo /sbin/shutdown -h now"
$ ssh [email protected] "sync && sync && /sbin/shutdown -h now"
Bash here document syntax to run multiple SSH command
The here document syntax tells the shell to read input from the current source (HERE) until a line containing only word (HERE) is seen:
ssh server1 << HERE command1 command2 HERE
Here is another example to run a multiple commands on a remote system:
ssh email@example.com << EOF date hostname cat /etc/resolv.conf EOF
With sudo command type:
ssh -t firstname.lastname@example.org << EOF sync sync sudo /sbin/shutdown -h 0 EOF
Pipe script to a remote server
Finally, create a script called “remote-box-commands.bash” as follows on your local server:
date hostname cat /etc/resolv.conf
Please note that the -t option will get rid of “Sorry, you must have a tty to run sudo/insert your-command-here” error message. You can also use pssh (parallel ssh) for executing ssh in parallel on a number of Linux/Unix/BSD servers. For more info see your ssh and bash command man page:
$ man ssh
$ man bash
$ man sudo
And there you have it, multiple bash shell command run using nothing but ssh client/sever model. A better option is to use the ansible tool.