bash 如何在 shell 脚本中使用 ssh?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29061/
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 do you use ssh in a shell script?
提问by Jon Ericson
When I try to use an sshcommand in a shell script, the command just sits there. Do you have an example of how to use sshin a shell script?
当我尝试在 shell 脚本中使用ssh命令时,该命令就在那里。你有一个如何在 shell 脚本中使用ssh的例子吗?
回答by Mats Fredriksson
Depends on what you want to do, and how you use it. If you just want to execute a command remotely and safely on another machine, just use
取决于你想做什么,以及你如何使用它。如果您只想在另一台机器上远程安全地执行命令,只需使用
ssh user@host command
for example
例如
ssh user@host ls
In order to do this safely you need to either ask the user for the password during runtime, or set up keys on the remote host.
为了安全地执行此操作,您需要在运行时询问用户密码,或者在远程主机上设置密钥。
回答by Jon Ericson
First, you need to make sure you've set up password-less (public key login). There are at least two flavors of ssh with slightly different configuration file formats. Check the sshmanpage on your system, consult you local sysadmin or head over to How do I setup Public-Key Authentication?.
首先,您需要确保已设置无密码(公钥登录)。ssh 至少有两种风格,配置文件格式略有不同。检查系统上的ssh联机帮助页,咨询本地系统管理员或转到如何设置公钥身份验证?.
To run sshin batch mode (such as within a shell script), you need to pass a command you want to be run. The syntax is:
要以批处理模式(例如在 shell 脚本中)运行ssh,您需要传递一个要运行的命令。语法是:
ssh host command
If you want to run more than one command at the same time, use quotes and semicolons:
如果要同时运行多个命令,请使用引号和分号:
ssh host "command1; command2"
The quotes are needed to protect the semicolons from the shell interpreter. If you left them out, only the first command would be run remotely and all the rest would be run on the local machine.
需要引号来保护分号免受 shell 解释器的影响。如果您将它们排除在外,则只会远程运行第一个命令,其余所有命令都将在本地计算机上运行。
回答by Iker Jimenez
回答by Steve M
You need to put your SSH public key into the ~/.ssh/authorized_keys
file on the remote host. Then you'll be able to SSH to that host password-less.
您需要将 SSH 公钥放入~/.ssh/authorized_keys
远程主机上的文件中。然后您就可以通过 SSH 连接到该主机而无需密码。
Alternatively you can use ssh-agent
. I would recommend against storing the password in the script.
或者,您可以使用ssh-agent
. 我建议不要将密码存储在脚本中。
回答by gmuslera
The easiest way is using a certificate for the user that runs the script.
最简单的方法是为运行脚本的用户使用证书。
A more complex one implies adding to stdin the password when the shell command asks for it. Expect, perl libraries, show to the user the prompt asking the password (if is interactive, at least), there are a lot of choices.
一个更复杂的方法是在 shell 命令要求时将密码添加到 stdin。期望,perl 库,向用户显示询问密码的提示(如果是交互式的,至少),有很多选择。