Search This Blog

Friday, June 24, 2011

ssh, scp without password to remote host

GIỚI THIỆU
Hôm nay định viết một script để tự động copy backup dữ liệu từ local host sang 1 host khác.
Việc copy thì dễ dàng có thể dùng các lệnh scp hay rsync. Tuy nhiên vấn đề khó khăn ở đây là các lệnh trên yêu cầu phải nhập password.

Phải làm sao để thực hiện các lệnh nói trên đến remote host mà không phải nhập password thì việc backup tự động mới khả thi được.

THỰC HIỆN

Nào hãy bắt đầu. Giả sử
localhost (192.168.241.63) - Máy source cần copy data
remotehost (192.168.241.246)- Máy đích cần copy data đến để backup
1) Từ localhost tạo một ssh rsa key pair cho host validation:  
[localhost]# ssh-keygen -t rsa 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: 82:c6:21:5b:9e:07:6e:6d:3b:66:47:eb:9e:ff:6a:bd root@localhost
 2) Copy public key đến remotehost dùng scp, chú ý đừng copy private key: 
[localhost]# scp ~/.ssh/id_rsa.pub 192.168.241.246:~ The authenticity of host '192.168.241.246 (192.168.241.246)' can't be established. RSA key fingerprint is 2e:43:dd:e8:72:8a:47:91:89:7f:b9:3a:94:ca:2a:27. Are you sure you want to continue connecting (yes/no)? yes Warning: Permanently added '192.168.241.246' (RSA) to the list of known hosts. root@192.168.241.246's password: id_rsa.pub                                    100%  395     0.4KB/s   00:00 
 public key đã copy OK, Bắt đầu connect đến máy remotehost

3) Connect đến máy remotehost dùng ssh: 
[localhost]# ssh root@192.168.241.246 root@192.168.241.246's password: Last login: Tue Feb 22 14:13:28 2011 from 192.168.241.249 [remotehost ~]#
 4) Kiễm tra nếu .ssh có tồn tại hay không, nếu không thì tạo mới: 
[remotehost]# ls -la ~/.ssh ls: cannot access /root/.ssh: No such file or directory
 Tạo mới

[remotehost]# mkdir .ssh [remotehost]# chmod 700 .ssh
5) Copy ssh public key vào file authorized keys và xóa nó khi hoàn thành: 
[remotehost]# cat ~/id_rsa.pub >> .ssh/authorized_keys [remotehost]# chmod 600 .ssh/authorized_keys [remotehost]# rm id_rsa.pub

6) Kiểm Tra: 
[localhost]# scp test.txt root@192.168.241.246:/hdd/ test.txt                                      100%    4     0.0KB/s   00:00   
 --Suu Tam--

No comments:

Post a Comment