简体   繁体   English

如何从本地计算机上的远程主机上特定(但可变)目录中执行脚本?

[英]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 我什至尝试加DIR=$1; cd $DIR DIR=$1; cd $DIR to the script and using DIR=$1; cd $DIR到脚本并使用

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

alas, none of these work. las,这些都不起作用。 How am I supposed to 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 . 另外,您可能还想看看古老的工具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 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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