[英]How do I get the result of a command from a remote server using ssh?
I am working in Linux bash (version 16.04.4 LTS).我在 Linux bash(版本 16.04.4 LTS)工作。 I am using ssh to connect to a remote server where I want to find for a specific file from a list of files (most recent file version) and then retrieve only the version.我正在使用 ssh 连接到我想从文件列表(最新文件版本)中查找特定文件的远程服务器,然后仅检索版本。 For example, considering this files on the remote server (server.com):例如,考虑远程服务器 (server.com) 上的此文件:
file-30.0-2.tar.xz
file-30.0-3.tar.xz
file-30.0-4.tar.xz
file-30.0-5.tar.xz
file-30.0-7.tar.xz
file-30.0-10.tar.xz
If I login directly in the remote server and If I try the following command it works.如果我直接登录到远程服务器,如果我尝试以下命令,它就可以工作。
ls file-*.tar.xz | sort -V | tail -n1 | grep -o '[[:digit:]]\+.[[:digit:]]\+.[[:digit:]]\+'
Output: 30.0-10
Output: 30.0-10
As I am working from another server I am using ssh to connect to remote server like this:当我在另一台服务器上工作时,我正在使用 ssh 像这样连接到远程服务器:
#!/bin/bash
set -euxo pipefail
ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -o PreferredAuthentications=publickey user@server.com "cd /myDir; \\
ls file-*.tar.xz | sort -V | tail -n1 | grep -o '[[:digit:]]\+.[[:digit:]]\+.[[:digit:]]\+')"
This command it's working and I get the same output as before (30.0-10).此命令正在运行,我得到与以前相同的 output (30.0-10)。
But I want to be able to pass that result (30.0-10) to outside the script and use it in the local server.但我希望能够将该结果 (30.0-10) 传递到脚本外部并在本地服务器中使用它。
Any ideas?有任何想法吗?
Simply assign the output of your script to a variable and later use that variable:只需将脚本的 output 分配给一个变量,然后使用该变量:
result="$(./yourscript)"
echo "Result from SSH = $result"
Print null delimited file list remotely, sort it by reverse major version, and patch version, so the latest is listed first远程打印 null 分隔文件列表,按反向主要版本和补丁版本排序,所以最新的排在最前面
read -r -d '' latest_archive < <(
ssh \
-o UserKnownHostsFile=/dev/null \
-o StrictHostKeyChecking=no \
-o PreferredAuthentications=publickey \
user@server.com \
printf '%s\\0' '/my/dir/file-*[[:digit:]].tar.xz' | sort -zt- -k2nr,3nr
)
How it works:怎么运行的:
printf '%s\\0' '/my/dir/file-*[[:digit:]].tar.xz'
: Prints null-delimited list of files matching the pattern. printf '%s\\0' '/my/dir/file-*[[:digit:]].tar.xz'
:打印与模式匹配的以空分隔的文件列表。| sort -zt- -k2nr,3nr
| sort -zt- -k2nr,3nr
: Pipe to sort -z
null-delimited entries, -t-
with dash -
as field delimiter, -k2nr,3nr
on 2nd field numerically, largest first, combined with 3rd field numerically and also largest first. | sort -zt- -k2nr,3nr
: Pipe 对-z
空分隔的条目进行排序, -t-
以破折号-
作为字段分隔符, -k2nr,3nr
在第二个字段上按数字排序,最大在前,与第三个字段在数字上组合,也是最大在前.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.