如何将 input/output 连接到 SSH 会话

How to connect input/output to SSH session

什么是能够直接发送到 STDIN 并从进程的 STDOUT 接收的好方法?我对 SSH 特别感兴趣,因为我想做以下事情:

[ssh into a remote server]
[run remote commands]
[run local commands]
[run remote commands]
 etc...

例如,假设我有一个本地脚本 "localScript",它将根据 "remoteScript" 的输出将我想要的下一个命令输出到远程 运行。我可以做类似的事情:

output=$(ssh myServer "./remoteScript")
nextCommand=$(./localScript $output)
ssh myServer "$nextCommand"

但是,如果在每一步都没有 closing/reopening SSH 连接,这样做会很好。

您使用的方法有效,但我认为您不能每次都重复使用相同的连接。但是,您可以这样做 using screen, tmux or nohup, but that would greatly increase the complexity of your script because you will now have to emulate keypresses/shortcuts. I'm not even sure if you can if you do directly in bash. If you want to emulate keypresses, you will have to run the script in a new x-terminal and use xdotool to emulate the keypresses.

另一种方法是通过 running the script on the remote server itself:

将整个脚本委托给 SSH 服务器
ssh root@MachineB 'bash -s' < local_script.sh

您可以将 SSH 输入和输出重定向到 FIFO-s,然后将它们用于 two-way 通信。

例如local.sh:

#!/bin/sh

SSH_SERVER="myServer"

# Redirect SSH input and output to temporary named pipes (FIFOs)
SSH_IN=$(mktemp -u)
SSH_OUT=$(mktemp -u)
mkfifo "$SSH_IN" "$SSH_OUT"
ssh "$SSH_SERVER" "./remote.sh" < "$SSH_IN" > "$SSH_OUT" &

# Open the FIFO-s and clean up the files
exec 3>"$SSH_IN"
exec 4<"$SSH_OUT"
rm -f "$SSH_IN" "$SSH_OUT"

# Read and write
counter=0
echo "PING${counter}" >&3
cat <&4 | while read line; do
    echo "Remote responded: $line"
    sleep 1
    counter=$((counter+1))
    echo "PING${counter}" >&3
done

简单remote.sh:

#!/bin/sh

while read line; do
    echo "$line PONG"
done