Dev1ce
Dev1ce

Reputation: 5944

Shell Script to run on Local and Remote machine

I am new to shell scripting,
I am trying to write a script that'll run on my local machine.

Few of it's commands are to run on my local and
then a few on the remote server.

Below is a sample script -
The 1st two will run on my local system,
rest of them are to run on the remote server.

eg -

scp -i permissions.pem someJar.jar ubuntu@ip:/var/tmp
ssh -i permissions.pem ubuntu@ip
sudo su
service someService stop
rm -rf /home/ubuntu/someJar.jar
rm -rf /home/ubuntu/loggingFile.log
mv /var/tmp/someJar.jar .
service someService start

As the script will run on my local machine,
How do make sure the 3rd and further commands take effect on the remote server and not on my machine?

Here's my sample.sh file -

scp -i permissions.pem someJar.jar ubuntu@ip:/var/tmp
SCRIPT="sudo su; ps aux | grep java; service someService stop; ps aux | grep java; service someService start; ps aux | grep java;"
ssh -i permissions.pem ubuntu@ip $SCRIPT

The scp is working, nothing is displayed after that.

Upvotes: 0

Views: 284

Answers (1)

Dmitri Sandler
Dmitri Sandler

Reputation: 1172

You need to pass the reset of the script as a parameter to SSH. Try this format:

SCRIPT="sudo su; command1; command2; command3;"
ssh -i permissions.pem ubuntu@ip $SCRIPT

See: http://linuxcommand.org/man_pages/ssh1.html

Hope this helps.


Update: The reason why you don't see anything after running the command is because sudo expects the password. To avoid this there are three solutions:

  1. Give ubuntu user needed permissions to perform all the tasks in the script.
  2. Pass the password to sudo under SCRIPT: echo 'password' | sudo su; ...
  3. Modify sudo-er file and allow ubuntu user to sudo without prompting for password. Run sudo visudo and add the following line: ubuntu ALL = NOPASSWD : ALL

Each system admin will have a different approach to this problem. I think everyone will agree that option 2 is the least secure. The reset is up to debate. In my opinion option 3 is slightly more secure. Yet, entire server is compromised if your key is compromised. The most secure is option 1. While it is painful to assign individual permissions, by doing so you are limiting your exposure to assigned permissions in case if your key is compromised.

One more note: It might be beneficial to replace ; with && in the SCRIPT. By doing so you will ensure that second command will run only if the first one finished successfully, third will run only if second finished successfully and so on.

Upvotes: 1

Related Questions