开发者

How can I execute a script from my local machine in a specific (but variable) directory on a remote host?

From a previous question, I have found that it is possible to run a local script on a remote host using:

ssh -T remotehost < localscript.sh

Now, I need to allow others to specify the directory in which the script will be run on the remote host.

I have tried commands such as

 ssh -T remotehost "cd /path/to/dir" < localscript.sh
 ssh -T remotehost:/path/to/dir < localscript.sh

and I have even tried adding DIR=$1; cd $DIR to the script and using

 ssh -T remotehost < localscript.sh "/path/to/dir/"

alas, none of these work. How am I supposed t开发者_开发百科o do this?


echo 'cd /path/to/dir' | cat - localscript.sh | ssh -T remotehost

Note that if you're doing this for anything complex, it is very, very important that you think carefully about how you will handle errors in the remote system. It is very easy to write code that works just fine as long as the stars align. What is much harder - and often very necessary - is to write code that will provide useful debugging messages if stuff breaks for any reason.

Also you may want to look at the venerable tool http://en.wikipedia.org/wiki/Expect. It is often used for scripting things on remote machines. (And yes, error handling is a long term maintenance issue with it.)


Two more ways to change directory on the remote host (variably):

echo '#!/bin/bash
cd "$1" || exit 1
pwd -P
shift
printf "%s\n" "$@" | cat -n
exit
' > localscript.sh

ssh localhost 'bash -s "$@"' <localscript.sh '/tmp' 2 3 4 5 
ssh localhost 'source /dev/stdin "$@"' <localscript.sh '/tmp' 2 3 4 5 

# make sure it's the bash shell to source & execute the commands
#ssh -T localhost 'bash -c '\''source /dev/stdin "$@"'\''' _ <localscript.sh '/tmp' 2 3 4 5 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜