bash 如何使用 ssh 连接到远程服务器并获取信息
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4884753/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to connect to a remote server using ssh and getting the information
提问by user57421
I'm trying to write a shell script using bash. I have multiple servers and each servers have multiple apps runnings on it. Each server also has specific app scripts to check/stop/start etc. All I want to do is that, do a ssh and connect to the remote server. Which I'm also able to do sucessfully and exceute the commands also..
我正在尝试使用 bash 编写一个 shell 脚本。我有多台服务器,每台服务器上都运行着多个应用程序。每个服务器也有特定的应用程序脚本来检查/停止/启动等。我想做的就是,做一个 ssh 并连接到远程服务器。我也能够成功完成并执行命令..
In some instance I need to check some process status on a remote machine, the app sepecific scripts already does that. But using my ssh when i try to execute that script I dont get any info ( it gets executed but no info is passed ). How do i get the information from the remote host and display on the local host here.
在某些情况下,我需要检查远程机器上的某些进程状态,应用程序特定脚本已经这样做了。但是当我尝试执行该脚本时使用我的 ssh 我没有得到任何信息(它被执行但没有信息被传递)。我如何从远程主机获取信息并在此处显示在本地主机上。
Any help on this is really appreciated.
对此的任何帮助都非常感谢。
Regards, Senny
问候, 森尼
回答by Shawn Chin
You can run remote commands and get results locallyby passing the command as a string to ssh.
您可以通过将命令作为字符串传递给 ssh来运行远程命令并在本地获取结果。
In your script, you can do:
在您的脚本中,您可以执行以下操作:
CMD_OUT=$(ssh user@remote_host "/path/to/script argument")
The command will be run remotely and the output store in the CMD_OUTvariable. You can then parse the output in your script to get the results you want.
该命令将远程运行,输出存储在CMD_OUT变量中。然后,您可以解析脚本中的输出以获得所需的结果。
To simplify usage of your script, you might want to set up passwordless sshso you don't have to type your password each time the script tries to run a remote command.
为了简化脚本的使用,您可能希望设置无密码 ssh,这样您就不必每次脚本尝试运行远程命令时都输入密码。

