使用ssh传输文件不用输入密码

时间:2022-05-30 05:04:23
有些时候,我们在复制/移动文件 到另一台机器时会用到scp,因为它比较安全。但如果每次

都要输入密码,就比较烦了,尤其是在script里。不过,ssh有另一种用密钥对来验证的方

式。下面写出我生成密匙对的过程,供大家参考。

第一步:生成密匙对,我用的是rsa的密钥。使用命令 "ssh-keygen -t rsa"
[user1@rh user1]$ ssh-keygen -t rsa 
Generating public/private rsa key pair. 
Enter file in which to save the key (/home/user1/.ssh/id_rsa): #回车即可
Created directory '/home/user1/.ssh'. 
Enter passphrase (empty for no passphrase): #回车即可
Enter same passphrase again: #回车即可
Your identification has been saved in /home/user1/.ssh/id_rsa. 
Your public key has been saved in /home/user1/.ssh/id_rsa.pub. 
The key fingerprint is: 
e0:f0:3b:d3:0a:3d:da:42:01:6a:61:2f:6c:a0:c6:e7 user1@rh.test.com 
[user1@rh user1]$



生成的过程中提示输入密钥对保存位置,直接回车,接受默认值就行了。接着会提示输入一

个不同于你的password的密码,直接回车,让它空着。当然,也可以输入一个。(我比较懒

,不想每次都要输入密码。) 这样,密钥对就生成完了。

其中公共密钥保存在 ~/.ssh/id_rsa.pub
私有密钥保存在 ~/.ssh/id_rsa


之后把这个密钥对中的公共密钥复制到你要访问的机器上去,并保存为 

~/.ssh/authorized_keys.
[user1@rh user1]$ scp ~/.ssh/id_rsa.pub rh1:/home/user1/.ssh/authorized_keys 
user1@rh1's password: 
id_rsa.pub 100% 228 3.2MB/s 00:00 
[user1@rh user1]$


之这样就大功告成了。之后你再用ssh scp sftp 之类的访问那台机器时,就不用输入密码

了,用在script上更是方便。

---第二种方式

[root@PC dandan]# ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):  #这里直接回车即可
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:
e4:9f:74:a1:c8:d6:6b:8d:de:fd:c7:ea:ef:73:dd:89 root@PC
The key's randomart image is:
+--[ RSA 2048]----+
|                 |
|                 |
|        .   .    |
|       + o . .   |
|        S + .    |
|       . o *     |
|          * . ..+|
|         o . E o*|
|          . ..+=B|
+-----------------+


[root@PC dandan]# ssh-copy-id 10.192.200.202 #这里输入你想不输入密码就能访问的IP
Address 10.192.200.202 maps to bogon, but this does not map back to the address - POSSIBLE BREAK-IN ATTEMPT!
root@10.192.200.202's password: #输入密码
Now try logging into the machine, with "ssh '10.192.200.202'", and check in:


  .ssh/authorized_keys


to make sure we haven't added extra keys that you weren't expecting.


下次就可以不用输入密码,直接访问了:

[root@PC dandan]# ssh 10.192.200.202
Address 10.192.200.202 maps to bogon, but this does not map back to the address - POSSIBLE BREAK-IN ATTEMPT!
Last login: Fri May  6 17:34:26 2016 from 10.192.200.42




转自 http://bbs.chinaunix.net/viewthread.php?tid=343905&extra=page%3D17%26filter%3Ddigest