简体   繁体   中英

Execute shell script in remote machine using ssh command with config file

I want to execute a shell script in remote machine and i achieved this using the below command,

ssh user@remote_machine "bash -s" < /usr/test.sh

The shell script executed properly in the remote machine. Now i have made some changes in script to get some values from the config file. The script contains the below lines,

#!bin/bash
source /usr/property.config
echo "testName"

property.config :

testName=xxx
testPwd=yyy

Now if i run the shell script in remote machine, i am getting no such file error since /usr/property.config will not be available in remote machine.

How to pass the config file along with the shell script to be executed in remote machine ?

Only way you can reference to your config file that you created and still run your script is you need to put the config file at the required path there are two ways to do it.

  1. If config is almost always fixed and you need not to change it, make the config locally on the host machine where you need to run the script then put the absolute path to the config file in your script and make sure the user running the script has permission to access it.

  2. If need to ship your config file every time you want to run that script, then may just simply scp the file before you send and call the script.

     scp property.config user@remote_machine:/usr/property.config ssh user@remote_machine "bash -s" < /usr/test.sh 

Edit

as per request if you want to forcefully do it in a single line this is how it can be done:

  • property.config

     testName=xxx testPwd=yyy 
  • test.sh

     #!bin/bash #do not use this line source /usr/property.config echo "$testName" 

Now you can run your command as John has suggested:

ssh user@remote_machine "bash -s" < <(cat /usr/property.config /usr/test.sh)

Try this:

ssh user@remote_machine "bash -s" < <(cat /usr/property.config /usr/test.sh)

Then your script should not source the config internally.


Second option , if all you need to pass are environment variables:

There are a few techniques described here: https://superuser.com/questions/48783/how-can-i-pass-an-environment-variable-through-an-ssh-command

My favorite one is perhaps the simplest:

ssh user@remote_machine VAR1=val1 VAR2=val2 bash -s < /usr/test.sh

This of course means you'll need to build up the environment variable assignments from your local config file, but hopefully that's straightforward.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM