引用地址: http://blog.chinaunix.net/u2/76835/showart.php?id=1359453
說明:藍色文字為本人添加
最近在編寫定時python指令碼時遇到一個問題。在該指令碼中,需要使用scp命令將本地的檔案複製到另一台機器中備份。但通常執行scp命令後都需要輸入使用者密碼,這樣在定時自動執行的python腳步中就不適用了。
後來在Internet中尋找相關資料,有資料[1]介紹在兩台機器的兩個使用者之間建立安全的信任關係後,可實現執行scp命令時不需要輸入使用者密碼。(該方法對ssh也適用)
以下為了討論方便,我們將執行scp命令的機器稱為Client,scp命令操作的遠端機器稱為Server。
以下是在機器Client的root和機器Server的root之間建立安全信任關係的步驟:
1. 在機器Client上root使用者執行ssh-keygen命令,產生建立安全信任關係的認證。
[root@Client root]# ssh-keygen -b 1024 -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:
49:9c:8a:8f:bc:19:5e:8c:c0:10:d3:15:60:a3:32:1c root@Client
[root@Client root]#
注意:在程式提示輸入passphrase時直接輸入斷行符號,表示無認證密碼。
上述命令將產生私密金鑰認證id_rsa和密鑰憑證id_rsa.pub,存放在使用者家目錄的.ssh子目錄中。
2. 將密鑰憑證id_rsa.pub複製到機器Server的root家目錄的.ssh子目錄中,同時將檔案名稱更換為authorized_keys。
[root@Client root]# scp -p .ssh/id_rsa.pub root@192.168.3.206:/root/.ssh/authorized_keys
root@192.168.3.206's password: <-- 輸入機器Server的root使用者密碼
id_rsa.pub 100% |**************************| 218 00:00
[root@Client root]#
在執行上述命令時,兩台機器的root使用者之間還未建立安全信任關係,所以還需要輸入機器Server的root使用者密碼。
經過以上2步,就在機器Client的root和機器Server的root之間建立安全信任關係。下面我們看看效果:
[root@Client root]# scp -p text root@192.168.3.206:/root
text 100% |**************************| 19 00:00
[root@Client root]#
it'ok!
備忘:ssh命令ssh [host]ssh [username@host]