0

I am in the process of trying to automate deployment to an AWS Server as a cool project to do for my coding course. I'm using ShellScript to automate different processes but when connecting to the AWS E2 Ubuntu server. When connected to the server, it will not do any other shell command until I close the connection. IS there any way to have it continue sending commands while being connected?

read -p "Enter Key Name: " KEYNAME

read -p "Enter Server IP With Dashes: " IPWITHD

chmod 400 $KEYNAME.pem

ssh -i "$KEYNAME.pem" ubuntu@ec2-$IPWITHD.us-east-2.compute.amazonaws.com

ANYTHING HERE AND BELOW WILL NOT RUN UNTIL SERVER IS DISCONNECTED

Adiii
  • 35,809
  • 6
  • 84
  • 87
Jeremyfto
  • 27
  • 6
  • Please include your code and clearly state what is not working. – codeforester Oct 26 '18 at 20:16
  • 3
    ah hem, Please read [mcve] and create/post the smallest/simpilest amount of code that demonstrates your problem. ;-) Good luck. – shellter Oct 26 '18 at 20:31
  • Possible duplicate of [What is the cleanest way to ssh and run multiple commands in Bash?](https://stackoverflow.com/questions/4412238/what-is-the-cleanest-way-to-ssh-and-run-multiple-commands-in-bash) – omajid Oct 26 '18 at 20:58
  • Possible duplicate of [Pass commands as input to another command (su, ssh, sh, etc)](https://stackoverflow.com/questions/37586811/pass-commands-as-input-to-another-command-su-ssh-sh-etc) – tripleee Oct 29 '18 at 05:22

1 Answers1

2

A couple of basic points:

A shell script is a sequential set of commands for the shell to execute. It runs a program, waits for it to exit, and then runs the next one.

The ssh program connects to the server and tells it what to do. Once it exits, you are no longer connected to the server.

The instructions that you put in after ssh will only run when ssh exits. Those commands will then run on your local machine instead of the server you are sshed into.

So what you want to do instead is to run ssh and tell it to run a set of steps on the server, and then exit.

Look at man ssh. It says:

ssh destination [command]

If a command is specified, it is executed on the remote host instead of a login shell

So, to run a command like echo hi, you use ssh like this:

ssh -i "$KEYNAME.pem" ubuntu@ec2-$IPWITHD.us-east-2.compute.amazonaws.com "echo hi"

Or, for longer commands, use a bash heredoc:

ssh -i "$KEYNAME.pem" ubuntu@ec2-$IPWITHD.us-east-2.compute.amazonaws.com <<EOF
  echo "this will execute on the server"
  echo "so will this"
  cat /etc/os-release
EOF

Or, put all those commands in a separate script and pipe it to ssh:

cat commands-to-execute-remotely.sh | ssh -i "$KEYNAME.pem" ubuntu@ec2-$IPWITHD.us-east-2.compute.amazonaws.com

Definitely read What is the cleanest way to ssh and run multiple commands in Bash? and its answers.

omajid
  • 9,528
  • 3
  • 37
  • 52