Tuesday, April 30, 2013

SSH - Non interactive


Over last coupe of days, I spent a few hours figuring out how to run shell scripts on Amazon EC2 Ubuntu instances. Heres how you do it.

Before trying this : Always keep an interactive ssh session with Amazon EC2 open so that you can always change the configuration again. In case of any mistakes in sshd_config the ssh would stop working.


What we want to achieve is following:


ssh -i !@#$$.pem ubuntu@ec2-**-**-***.region@amazonaws.com 'bash -s' < ./script_name.sh

The main issue with running the above command is that while using an interactive session

i.e ssh -i !@#$$.pem ubuntu@ec2-**-**-***.region@amazonaws.com

>ubuntu@**.**.***> ./script_name.sh

The interactive ssh session loads all the environmental variables saved in the ~/.bashr and ~/.profile while executing the script using the non interactive session these files are not read.

The solution is to create a new file called environment under 

~/.ssh/environment

PATH=path to the folders required for running the script

Now in order to force ssh to load this environment we have to
add following line to /etc/ssh/sshd_config file 

PermitUserEnvironment yes

and then restart the ssh using 

/etc/init.d/ssh restart

On the client terminal check if the environment is properly set using

ssh -i !@#$$.pem ubuntu@ec2-**-**-***.region@amazonaws.com "env"

 And you are ready to run shell scripts on Amazon EC2 instance remotely through ssh in a non interactive way.

No comments:

Post a Comment