繁体   English   中英

是否有可能创建一个BASH脚本,它将ssh到远程机器并继续在那里做事?

[英]Is it possible to create a BASH script which will ssh into a remote machine and continue doing things there?

我自己尝试过这样做但是在脚本登录到远程机器后,脚本停止了,这是可以理解的,因为远程机器不知道脚本,但可以这样做吗?

谢谢

试试here-doc

ssh user@remote << 'END_OF_COMMANDS'
echo all this will be executed remotely
user=$(whoami)
echo I am $user
pwd
END_OF_COMMANDS

当你说“继续在那里做事”时,你可能意味着简单地与远程会话进行交互,然后:

expect -c 'spawn ssh user@host; interact'

有多种方式:

  1. ssh user @ remote <script.txt
  2. scp script user @ remote:/tmp/somescript.sh; ssh user @ remote /tmp/somescript.sh
  3. 写一个期望 脚本

对于前2个选项,出于自动化原因,我建议使用公钥/私钥对进行登录。

您需要在ssh调用结束时提供远程命令:

$ ssh user@remote somecommand

如果您需要实现一系列命令,那么编写脚本会更容易,将其复制到远程计算机(使用例如scp )并如上所示调用它。

在这种情况下我更喜欢perl:

use Net::SSH::Perl;
my $ssh = Net::SSH::Perl->new($host);
$ssh->login($user, $pass);
my($stdout, $stderr, $exit) = $ssh->cmd($cmd);

它不易出错,并且在捕获命令的stdout,stderr和退出状态时可以更好地控制。

你的~/.profile (或者~/.bash_profile )中的这样的东西应该可以解决这个问题:

function remote {
    ssh -t -t -t user@remote_server "$*'"
}

然后打电话

remote somecommandofyours

我通过使用declare -f将整个函数传递给ssh到远程服务器然后在那里执行来解决了这个问题。 这实际上可以非常简单地完成。 唯一需要注意的是,您必须确保函数使用的任何变量都在其中定义或作为参数传入。 如果函数使用任何类型的环境变量,别名,其他函数或在其外部定义的任何其他变量,它将无法在远程计算机上运行,​​因为那些定义不存在。

那么,我就是这样做的:

somefunction() {
    host=$1
    user=$2
    echo "I'm running a function remotely on $(hostname) that was sent from $host by $user"
}

ssh $someserver "$(declare -f somefunction);somefunction $(hostname) $(whoami)"

注意,如果你的函数确实使用了任何类型的'全局'变量,那么可以在声明函数之后用sed或者我喜欢的perl进行模式替换来替换它们。

declare -f somefunction | perl -pe "s/(\\$)global_var/$global_var/g"

这将用函数的值替换对函数中global_var的任何引用。

干杯!

暂无
暂无

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

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