如何在 shell 脚本中使用 ssh?
当我尝试在 shell 脚本中使用 ssh 命令时,该命令就在那里。 您有如何在 shell 脚本中使用 ssh 的示例吗?
When I try to use an ssh command in a shell script, the command just sits there. Do you have an example of how to use ssh in a shell script?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
取决于您想做什么以及如何使用它。 如果您只想在另一台计算机上远程安全地执行命令,只需使用
例如
为了安全地执行此操作,您需要在运行时询问用户密码,或者在远程主机上设置密钥。
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
for example
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.
首先,您需要确保您已设置无密码(公钥登录)。 至少有两种风格的 ssh,其配置文件格式略有不同。 检查系统上的 ssh 联机帮助页,咨询本地系统管理员或前往 如何设置公钥身份验证?。
要以批处理模式(例如在 shell 脚本中)运行 ssh,您需要传递要运行的命令。 语法是:
如果要同时运行多个命令,请使用引号和分号:
需要使用引号来保护分号免受 shell 解释器的影响。 如果您忽略它们,则只有第一个命令将远程运行,其余所有命令将在本地计算机上运行。
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 ssh manpage on your system, consult you local sysadmin or head over to How do I setup Public-Key Authentication?.
To run ssh in batch mode (such as within a shell script), you need to pass a command you want to be run. The syntax is:
If you want to run more than one command at the same time, use quotes and semicolons:
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.
您需要将 SSH 公钥放入远程主机上的
~/.ssh/authorized_keys
文件中。 然后您就可以无需密码地通过 SSH 连接到该主机。或者,您可以使用
ssh-agent
。 我建议不要将密码存储在脚本中。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.Alternatively you can use
ssh-agent
. I would recommend against storing the password in the script.您可以使用
expect
命令来填充用户名/密码信息。You can use
expect
command to populate the username/password info.最简单的方法是为运行脚本的用户使用证书。
更复杂的是,当 shell 命令要求输入密码时,将密码添加到标准输入中。 期望,perl库,向用户显示询问密码的提示(如果是交互式的,至少),有很多选择。
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.