How to use ssh command in shell script?

2019-02-19 05:00发布

I know that we shuld do ssh user@target but where do we specify the password ?


Hmm thanks for all your replies. My requirement is I have to start up some servers on different machines. All servers should be started with one shell script. Well, entering password every time seems little bad but I guess I will have to resort to that option. One reason why I don't want to save the public keys is I may not connect to same machines every time. It is easy to go back and modify the script to change target addresses though.

标签: ssh shell
6条回答
戒情不戒烟
2楼-- · 2019-02-19 05:07

If you really want to use password authentication , you can try expect. See here for an example

查看更多
一纸荒年 Trace。
3楼-- · 2019-02-19 05:12

SSH Keys are the standard/suggested solution. The keys must be setup for the user that the script will run as.

For that script user, see if you have any keys setup in ~/.ssh/ (Key files will end with a .pub extension)

If you don't have any keys setup you can run:

ssh-keygen -t rsa

which will generate ~/.ssh/id_rsa.pub (the -t option has other types as well)

You can then copy the contents of this file to ~(remote-user)/.ssh/authorized_keys on the remote machine.

As the script user, you can test that it works by:

ssh remote-user@remote-machine

You should be logged in without a password prompt.

Along the same lines, now when your script is run from that user, it can auto SSH to the remote machine.

查看更多
淡お忘
4楼-- · 2019-02-19 05:16

This cannot be done with a simple ssh command, for security reasons. If you want to use the password route with ssh, the following link shows some scripts to get around this, if you are insistent:

Scripts to automate password entry

查看更多
做自己的国王
5楼-- · 2019-02-19 05:23

The ssh command will prompt for your password. It is unsafe to specify passwords on the commandline, as the full command that is executed is typically world-visible (e.g. ps aux) and also gets saved in plain text in your command history file. Any well written program (including ssh) will prompt for the password when necessary, and will disable teletype echoing so that it isn't visible on the terminal.

If you are attempting to execute ssh from cron or from the background, use ssh-agent.

查看更多
走好不送
6楼-- · 2019-02-19 05:29

The best way to do this is by generating a private/public key pair, and storing your public key on the remote server. This is a secure way to login w/o typing in a password each time. Read more here

查看更多
Animai°情兽
7楼-- · 2019-02-19 05:34

The way I have done this in the past is just to set up a pair of authentication keys.

That way, you can log in without ever having to specify a password and it works in shell scripts. There is a good tutorial here:

http://linuxproblem.org/art_9.html

查看更多
登录 后发表回答