How do you use ssh in a shell script?

旧街凉风 提交于 2019-12-18 12:17:24

问题


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?


回答1:


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.




回答2:


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:

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.




回答3:


You can use expect command to populate the username/password info.




回答4:


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.




回答5:


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.



来源:https://stackoverflow.com/questions/29061/how-do-you-use-ssh-in-a-shell-script

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!