Connect and run commands over SSH using script
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 [email protected]:xxxxxxxxx/bimaster.git 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.
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 SSHexpect
waits until the matching text is shown on screensend
enters the text given, which can be a password or command to be runexpect
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"
.
I would suggest you use ssh-copy-id
to grant your computer automated ssh access to the remote server of your choice. The utility is found under /usr/bin/
on most systems (including recent versions of macOS). On older macOS versions you can run
cat ~/.ssh/id_rsa.pub |
ssh [email protected] "[ -d ~/.ssh ] || mkdir ~/.ssh; cat >> ~/.ssh/authorized_keys"
Then it is trivial to execute a script already on the remote server:
ssh -t [email protected] /Users/johnfoo/myscript.sh
If necessary you can create such script locally and use scp
to transfer it to the remote server at the location of your choice:
scp myscriptscript.sh [email protected]:/Users/johnfoo/myscript.sh
But if your script is relatively short - I would simply run it from the terminal session invoking a here document after your ssh command:
ssh -t [email protected] <<< END_OF_COMMAND
ssh-agent bash
ssh-add bi-master
cd /home/trans/bimaster
git status
git pull [email protected]:xxxxxxxxx/bimaster.git master
END_OF_COMMAND