简体   繁体   English

在远程机器上运行命令并将其 output 存储在远程机器上的变量中

[英]Run a command on remote machine and store its output in variable on remote machine

I want to capture number of rules of iptables that start with specific pattern in comment and then delete them.我想在评论中捕获以特定模式开头的 iptables 规则的数量,然后将其删除。 This is what I want to achieve.这就是我想要实现的。 Here is my bash script这是我的 bash 脚本

ssh -o "StrictHostKeyChecking no" root@$ip_address << EOF
echo "Now Removing your IPTables";

#storing output in input variable
input=$(iptables -nL INPUT --line-number | grep ip.* | cut -d " " -f1 | xargs)

#converting variable into an array
arr1=($input);

#loop through each element of array
echo "length:${#arr1[@]}";
for (( i="${#arr1[@]}"-1;i >=0; i-- ));
do
    echo "$i:${arr1[$i]}"
    iptables -D INPUT $i;
done;
EOF

Problem is the iptables command is not being executed on the remote machine and the output shows the length of arr1 is 0. But I am sure iptables has rules with my desired pattern.问题是远程计算机上没有执行 iptables 命令,并且 output 显示 arr1 的长度为 0。但我确信 iptables 具有符合我所需模式的规则。

Error being shown in terminal:终端显示错误:

-bash: line 9: 3: command not found

Adding 2>&1 in the end of command also not working:在命令末尾添加2>&1也不起作用:

input=$(iptables -nL INPUT --line-number | grep ip.* | cut -d " " -f1 | xargs 2>&1)

TL;DR: Use <<"EOF" instead of <<EOF . TL;DR:使用<<"EOF"而不是<<EOF

Your Here-Document will expand all variables and evaluate all subshells before the script is even sent to your ssh server.您的 Here-Document 将在脚本发送到您的 ssh 服务器之前展开所有变量并评估所有子 shell。

Consider the following script:考虑以下脚本:

ssh user@servername <<EOF
    echo "$(hostname)"
EOF

This will not print servername (the name of the computer you are connecting to) but the name of your localhost instead (the name of the computer you working on).不会打印servername (您正在连接的计算机的名称),而是您的 localhost 的名称(您正在使用的计算机的名称)。

Before ssh is executed, the subshell $(hostname) is executed.在执行ssh之前,会执行子 shell $(hostname) The resulting string " echo localhostname " is then passed to ssh and executed on the remote server.然后将生成的字符串“ echo localhostname ”传递给ssh并在远程服务器上执行。

To fix the problem you have to escape the $ inside the Here-Document or use a literal Here-Document:要解决此问题,您必须转义 Here-Document 中的$或使用文字 Here-Document:

ssh user@servername <<"EOF"
    echo "$(hostname)"
EOF

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

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