Bash 使用 heredocs 或更好的方法编写脚本

Bash scripting with heredocs or better approach

我需要 运行 里面的一些命令

ssh->ssh->clientprogram->loop command

这是我执行命令的要求。

  1. 将输入参数发送到第一个 ssh 服务器,捕获该命令的输出(这是一个 bash 脚本,相互依赖于同一路径中的其他脚本,并且在 $path 变量中可用。我确实检查过用 echo $PATH)
  2. 将step1的命令输出ip提供给第二个ssh命令。
  3. 循环 n 次并在循环内启用客户端并执行一系列命令并捕获两个命令的输出并验证第二个命令的输出(例如:一系列命令是:rm 文件;ls - > 检查文件是否存在然后重复相同直到 n 次迭代)
  4. Step3 应该根据选择执行(例如:创建文件或删除文件)。这个变量应该是用户在开始时的选项。

截至目前,我能够放置所有静态 IP 并能够执行一个命令

 ssh_to_server () {

        remote_output=$(ssh -t root@10.25.55.10 << "EOF"
            # looking for command to capture output of input entry 1 and proceed further like
           command_output=$(/tmp/user/script ) # this is not working. getting file or directory not found.
            ssh -t user@10.50.10.76 << "EOF1"
                clientprogram <<-"EOF2"
                  loop;then
                    command1  # based on "option"
                     command2  # checking if the delete or create operation is success.
                  end loop
                  /exit . # exit from the client program
                EOF2
            EOF1
    EOF)
    }
ssh_to_server "input" "option"

以上代码中的示例 IP。

我能够在客户端程序中执行命令并捕获输出,但我需要的是:

  1. 捕获第一个 ssh 服务器中命令的 ip 输出,并将其动态传递给第二个 ssh 服务器。
    1. 将选项从用户传递到客户端程序或第二个服务器以创建或删除文件。

注意:第二个 ssh 服务器不允许来自除第一个服务器之外的任何其他 ip 的 ssh。因此,ssh 隧道和其他隧道将无法正常工作。如果有任何更好的方法来处理使用其他脚本语言(Python、Perl)或Java(我可以创建一个 jar)是可以接受的。

有两个独立的传输

执行此操作的简单方法是分为两个单独的步骤,如:

printf -v args_q '%q ' "$@"  # store our script's arguments in a string
host2_ip=$(ssh host1 get_host2_ip)
ssh -o"ProxyJump host1" "$host2_ip" "bash -s $args_q" <<'EOF'
  ...inner command for host2 goes here...
EOF

由于 -o"ProxyJump host1",到 host2_ip 的连接是从 host1 建立的;但是,host2_ip 会首先返回到系统 运行 脚本。


一次运输

如果您需要比这更高的性能,那就是 ControlSocket 功能的用武之地。

printf -v args_q '%q ' "$@"  # store our script's arguments in a string
ssh_common_args=( -o"ControlMaster=yes" -o"ControlPath $HOME/.ssh/socket-%r@%h:%p" )
host2_ip=$(ssh "${ssh_common_args[@]}" host1 get_host2_ip)
ssh "${ssh_common_args[@]}" -o"ProxyJump host1" "$host2_ip" "bash -s $args_q" <<'EOF'
  ...inner command for host2 goes here...
EOF

这样,同一个连接用于 host1 上的 通道调用——第一个连接用于检索 host2 IP 地址,第二个连接用于运行你的实际远程命令。