SSH自动输入密码,取消首次连接确认

SSH是最常用的工具了,ssh username@ipAddress 即发起到远程主机的访问。随后输入远程机器的密码即可连接,同时,首次连接到远程主机还会要求获得远程主机的公钥,这时必须手动输"yes".  下图是完整的连接过程。

ha@ha-To-be-filled-by-O-E-M:~$ ssh [email protected]
The authenticity of host '192.168.1.5 (192.168.1.5)' can't be established.
ECDSA key fingerprint is SHA256:yIprcaFyxAR7lY/uXm6p6zMfdtXFSfb1DHI+Buf3MQ0.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '192.168.1.5' (ECDSA) to the list of known hosts.
[email protected]'s password: 
Welcome to Ubuntu 18.04.1 LTS (GNU/Linux 4.15.0-32-generic x86_64)

在自动化运维时,需要在一个脚本里自动连接到远程主机,这时候是没有人等在屏幕前输密码和yes指令的。

自动输入密码可以使用sshpass工具(不是自带工具,可以运行 sudo apt-get install sshpass 安装)。使用示例如下,sshpass可以自动把密码传递给ssh。

sshpass -p  ssh @

 

但是对于首次连接的主机,或者ip地址改变后的主机,还是需要输入yes确认密钥。禁用认证确认步骤可以解决这一问题。

方法一:设置取消严格的key检查
can set the StrictHostKeyChecking option to no on the command line, and/or send the key to a null known_hosts file. You can also set these options in your config file, either for all hosts or for a given set of IP addresses or host names.

ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no


方法二:在配置文件中设置对某些连接的地址的key自动跳过
To disable (or control disabling), add the following lines to the beginning of /etc/ssh/ssh_config.

Host 192.168.0.*
   StrictHostKeyChecking no
   UserKnownHostsFile=/dev/null


Options:
The Host subnet can be * to allow unrestricted access to all IPs.
Edit /etc/ssh/ssh_config for global configuration or ~/.ssh/config for user-specific configuration.

 

这样,如果在命令行中取消主机密钥检查,并且用sshpass传递密码,完整的用法就是:

sshpass -p ${password} ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no  $user@$IPAdd

Ref:

http://www.freeoa.net/osuport/netmanage/linux-ssh-auto-accept-pub-key-firstime_2567.html

你可能感兴趣的:(基础知识)