ssh 无密码登录

来源:互联网 发布:java里的sum什么意思 编辑:程序博客网 时间:2024/05/07 08:04

1、单向无密码登录
1.1、情景:服务器A需要单向无密码访问服务器B。
1.2、原理:服务器A生成秘钥对,将公钥传给B,将私钥留给自己,当登录的时候,服务器B将使用A的公钥验证A的私钥,从而认证成功。
1.3、操作方法:
(1)服务器A生成秘钥对:
[root@mysqlcluster ~]# ssh-keygen -t rsa
    Generating public/private rsa key pair.
    Enter file in which to save the key (/root/.ssh/id_rsa):
    Created directory ‘/root/.ssh’.
    Enter passphrase (empty for no passphrase):
    Enter same passphrase again:
    Your identification has been saved in /root/.ssh/id_rsa.
    Your public key has been saved in /root/.ssh/id_rsa.pub.
    The key fingerprint is:
    0e:4c:ec:e3:04:98:b0:71:00:91:75:57:ee:56:a1:82 root@mysqlcluster
执行上面一步,会在~/.ssh目录下生成两个文件id_rsa和id_rsa.pub, 其中id_rsa是私钥,保存在本机;id_rsa.pub是公钥,是要上传到远程服务器的。
(2)将公钥传给服务器B:
远程服务器B上如果没有.ssh目录的话,需要手动创建:
    [root@www1bak ~]# mkdir .ssh
    [root@www1bak ~]# chmod 755 .ssh
然后从服务器A上传公钥文件到远程服务器B:
    [root@mysqlcluster ~]# scp .ssh/id_rsa.pub root@192.168.15.234:/root/.ssh/authorized_keys
    The authenticity of host ’192.168.15.234 (192.168.15.234)’ can’t be established.
    RSA key fingerprint is c9:ef:0c:1b:ac:6c:ef:84:a4:a7:e5:d1:20:58:c8:73.
    Are you sure you want to continue connecting (yes/no)? yes                              
    Warning: Permanently added ’192.168.15.234′ (RSA) to the list of known hosts.    //这一步会将远程服务器B加入到本机(服务器A)的known_hosts列表中
    root@192.168.15.234′s password:
    id_rsa.pub
(3)测试免秘钥登录
上传完公钥文件到远程后,马上从服务器A登陆到服务器B,如果没有输入密码登陆到了服务器B,表示成功,如果还要输入密码,则请检查远程服务器B上的.ssh目录权限是否为700,上传的远程服务器上的公钥名是否改为了authorized_keys,权限是否为644。


2、多服务器相互无密码访问
原理同上。

3、shell中如何使用ssh

在shell中执行远程ssh命令格式如下: ssh user@ip "cmd1;cmd2"

注意:当执行多个命令,使用分号分割开。


4、例子

#!bin/bash
ssh root@172.28.18.40 "cd /home/wj/IM/IM_V42.3/;  sh rm.sh"
scp AuthServer BrokerServer MessageServer HttpServer OfflineServer IosPushServer root@172.28.18.40:/home/wj/IM/IM_V42.3/
ssh root@172.28.18.40 "cd /home/wj/IM/IM_V42.3/;  sh ReStart.sh"



0 0