ssh免密码登录远程服务器

时间:2022-04-26
本文章向大家介绍ssh免密码登录远程服务器,主要内容包括最简单的操作、使用sshpass非交互的ssh密码验证、基本概念、基础应用、原理机制和需要注意的事项等,并结合实例形式分析了其使用技巧,希望通过本文能帮助到大家理解应用这部分内容。

最简单的操作

ssh免密码登录的原理是把本地电脑的公钥放在宿主机,然后使用本地电脑的私钥去认证。

在本地电脑执行 /usr/bin/ssh-keygen -t rsa,安装提示一直回车即可,最后会看到~/.ssh目录下多了几个文件id_rsa (私钥) id_rsa.pub (公钥).

在本地电脑执行 scp ~/.ssh/id_rsa.pub user@remote_server:拷贝~/.ssh/id_rsa.pub到需要远程登录的服务器的家目录下。

使用密码登录远程服务器,执行mkdir -p ~/.ssh; cat ~/id_rsa.pub >>~/.ssh/authorized_keys; chmod 700 ~/.ssh; chmod 600 >>~/.ssh/authorized_keys.

退出,再尝试登录,应该就不需要输入密码了。

更详细解释和问题解决请看原文链接http://blog.genesino.com/2012/02/ssh-login-without-passwd/。

使用sshpass非交互的ssh密码验证

sshpass是非交互性ssh登录工具,把密码作为参数或存储在配置文件中提供,省去了多次输入密码的麻烦。

sshpass安装:

wget 'https://downloads.sourceforge.net/project/sshpass/sshpass/1.06/sshpass-1.06.tar.gz?r=https%3A%2F%2Fsourceforge.net%2Fprojects%2Fsshpass%2F&ts=1496021628&use_mirror=jaist' -O sshpass-1.06.tar.gz

tar xvzf sshpass-1.06.tar.gz

cd sshpass*
./configure --prefix=/install_path
make
make install
# 加入环境变量

(后台回复 环境变量 获取环境变量的解释和应用)

# 登录远程服务器
sshpass -p 'password' ssh user@remote_host  

# execute command from remote server
sshpass -p 'password' ssh user@remote_host 'ls' 

# Remote login multiple servers; -tt should be used when error 
# 'Pseudo-terminal will not be allocated because stdin is not a terminal' appears.
sshpass -p 'password' ssh -tt user@remote_host 
    'source ~/.bashrc; sshpass -p "password" ssh -tt user@another_remote_host "Execute other command"'