How do I pass a variable from my local server to a

2019-08-15 07:24发布

问题:

I am trying to pass a variable from my local server (location1) to a remote server (location2). The purpose of the code is to copy a file from the remote server from a predefined location. In simpler terms, I want to copy files from location2 to location1 using a predefined path where location1 is on the local server and location2 is a remote server. See the code segment:

 $location1=somewhere/on/local_server
 $location2=somewhere/on/remote_server

 sshpass -p "password" ssh username@74.11.11.11 'su -lc "cp -r $location2 $location1";'

The error I get is that both $location1 and $location2 are undefined. Also, I DON'T want to manually type the location paths because they could change at any time and it would be a pain to change them in the code if done manually.

回答1:

You can do:

sshpass -p "password" ssh username@74.11.11.11 "su -lc \"cp -r $location2 $location1\""


回答2:

You can try letting the remote shell read variables from input:

location1=somewhere/on/local_server
location2=somewhere/on/remote_server
printf '%s\n%s\n' "$location1" "$location2" | \
    sshpass -p "password" ssh username@74.11.11.11 'read location1; read location2; su -lc "cp -r \"$location2\" \"$location1\"";'

Take notice that I added double-quotes to variables. It could work even if pathnames have spaces on them.



回答3:

You location1/2 declaration have a syntax error. The "$" must not be used while assigning the value. That's why you get an undefined value:

location1=somewhere/on/local_server
location2=somewhere/on/remote_server