MacOS – Connect and run commands over SSH using script

bashcommand linemacosscriptterminal

I'm using a series of commands for deploying my files to production. This is currently done manually.

Is it possible to make these commands into an executable file? So that I don't have to copy paste these commands each and every time.

When the first line is executed i.e., connecting to the root server, it will ask for the password and I have to paste the password: xxxxxxxxxxxxxx

ssh root@server
pwd: xxxxxxxxxxxxxx
ssh-agent bash
ssh-add bi-master
cd /home/trans/bimaster
git status
git pull master

Note : I'm the admin of the server, Since the project is been done by different teams as of now, we have decided to do manual deployment (cannot use Jenkins or any other tools for automated deployment), as we have to check the status of some files.

Best Answer

You can use ‘expect’ to enter the SSH password when prompted. Changes to your script are bolded.

#!/usr/bin/expect -f
spawn ssh root@server
expect "*: "
send "xxxxxxxxxxxxxx
expect "$ "
send "… commands

spawn starts the command as normal, which in this case is SSH
expect waits until the matching text is shown on screen
send enters the text given, which can be a password or command to be run
expect waits for the shell to be shown (this should be changed to match against your shell $PS1)

Save this file, add the executable bit (chmod +x /path/to/file) and open to run the commands.

However, instead of this, you should be using SSH keys to connect to the server without entering a password, and the commands you wish to execute over SSH should be in a script on the server which can be run. Set up SSH keys, then you can run a remote script with ssh -t root@server "/path/to/script".