---
title: "如何在两台linux服务器之间用RSA键对的方法SSH/SCP不需密码"
author: "shmayl"
date: "2010-11-08T12:21:30Z"
tags: []
categories: ["操作系统"]
slug: "linux-rsa-ssh-scp"
draft: false
lastmod: "2010-11-08T12:21:30Z"
id: 805490
url: "https://shmayl.iteye.com/blog/805490"
---

两台linux服务器A和B

　　都编译安装上最新版的openSSH(建议)

　　openSSH的默认设置是允许root可以直接login. (PermitRootLogin yes),暂且保留这种设置，我们先考虑如何

　　用SSH直接从A到B不需要密码，假设用用户root登录到A，想SSH到B也作为root不需要密码。

　　1。 分别从A和B上登录作为root后运行/usr/bin/ssh-keygen -t rsa，目的是简单地在/root下创建目录.ssh,当提示输入

　　passphase时打入两次回车。这将生成/root/.ssh/identity and /root/.ssh/identity.pub

　　2。 先测试一下，从A登录作为root，打入#ssh B,会要求提示root password。

　　3。 现在从A登录作为root，运行scp /root/.ssh/identity.pub B:/root/.ssh/authorized\_keys。

　　文件名必须不能弄错。

　　4。现在再从A运行#ssh B则不需要密码了：)

　　基本原理：

　　1。 如果你希望从A作为用户user1 SSH 到B 作为用户user2, 若要用RSA键对法认证且不需要密码，则B上的ssh

　　后台程序拿出~user2/.ssh/authorized\_keys中的与A有关的RSA公钥来对A上的以user1身份运行的ssh客户程序

　　进行挑战，前面我们已经把A上的identity.pub拷贝到B上作为authorized\_keys了。则A保持私钥identity,而B

　　上的sshd又拿出A的公钥来挑战，因此成功，你可以加很多行到authorized\_keys以允许其它服务器的公钥可以加

　　进来。

　　常见应用举例：

　　1。 在A上以用户root SSH到B上作为普通用户user而不是root,因为为了安全，有时不需要作为root，只需要作

　　为普通用户不需要密码以完成相应工作即可。

　　登录作为root在A上

　　A# scp /root/.ssh/identity.pub [user@B:/home/user/.ssh/authorized\_keys](mailto:user@B:/home/user/.ssh/authorized_keys)

　　2. tar一批文件从A到B。

　　A# tar cvf - /etc | ( ssh B tar xvf -)

　　3. 运行A上的cronjob，对某文件作改动后传到B

　　0 1 * * * cat /etc/shadow | awk -F: {print $1":"$2} | (ssh B cat &gt; /home/passwd)

　　常见问题：

　　1。 这种方式的SSH需要B上的sshd\_config中允许直接的root login (PermitRootLogin yes).

　　2. 我有服务器A和其它服务器B，C，D。我想从A SSH到这些服务器但不要自动，最好输入RSA passphase，但太

　　麻烦，怎么办?

　　a. 要A上运行ssh-keygen时输入passphase字。

　　b. 要登录到A上后运行A#ssh-agent bash

　　c. 再运行ssh-add加passphase进入内存

　　d. 再运行ssh B or SSH C or SSH D,则不再需要密码，密码对只需输一次

　　e. 最后退出shell前输入ssh-agent -k 。

      转帖自：[http://hi.baidu.com/dianhui/blog/item/969208954925d90f7bf4809f.html](http://hi.baidu.com/dianhui/blog/item/969208954925d90f7bf4809f.html)