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

一个人想着一个人 提交于 2019-12-13 02:36:54

问题


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


来源:https://stackoverflow.com/questions/23996742/how-do-i-pass-a-variable-from-my-local-server-to-a-remote-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!