標籤:linux ssh
1、產生本機伺服器ssh私密金鑰,如已存在,可忽略。
$ssh-keygen -t rsaGenerating public/private rsa key pair.Enter file in which to save the key (/root/.ssh/id_rsa):
一路斷行符號,會在本地家目錄~/.ssh/產生密鑰檔案,檢查如果存在,則可忽略。(更多ssh-keygen使用協助,見ssh-keygen -h)
產生以後,如下:
$ls -ltra ~/.ssh/id_rsa*-rw-r--r--. 1 root root 408 May 4 13:20 /root/.ssh/id_rsa.pub-rw-------. 1 root root 1675 May 4 13:20 /root/.ssh/id_rsa
2、ssh登陸遠端伺服器,開通防火牆,如已開通,可忽略
$/sbin/iptables -I INPUT -i eth0 -s 10.10.10.10 -p tcp -m tcp --dports 22 -j ACCEPT
開通防火牆以後,確認本地ssh 10.10.10.11 22能通(假設本機伺服器IP:10.10.10.10,遠端伺服器IP為:10.10.10.11)
3、確認遠端伺服器存在~/.ssh/authorized_keys檔案及對應目錄,不存在則建立、否者可忽略。
$ls -ltra ~/ | grep ssh drwx------. 2 root root 4096 May 4 13:38 .ssh$ls -ltr .ssh/authorized_keys -rw-------. 1 root root 408 May 4 13:38 .ssh/authorized_keys
注意:檔案~/.ssh/authorized_keys的許可權必須為600,目錄~/.ssh/許可權為700,否者信任會失效。
4、拷貝本機產生的公開金鑰檔案(~/.ssh/id_rsa.pub)內容追加到遠端伺服器~/.ssh/authorized_keys中
$cat .ssh/id_rsa.pub
粘貼如上檔案中的內容至目標伺服器~/.ssh/authorized_keys中。
5、如覺得麻煩,可忽略3-4兩步操作,使用ssh-copy-id命令一步到位。
$ssh-copy-id -i ~/.ssh/id_rsa.pub 10.10.10.11$ssh-copy-id -hUsage: /usr/bin/ssh-copy-id [-i [identity_file]] [[email protected]]machine
完成以後,正常情況下,我們就可以本地無密碼直接ssh登陸遠端伺服器了。
如將本機使用者luser公開金鑰內容追加到遠端使用者ruser家目錄~/.ssh/authorized_keys檔案中,那麼本機使用者就可以ssh [email protected](遠端ip),需要訪問使用者的對應關係一定要搞清楚了。
6、非正常情況,我們會遇到一些錯誤,即使按照上面的步驟做完了以後,依然無法無密碼登陸。
確認防火牆OK
確認遠端~/.ssh/authorized_keys檔案許可權正確,並沒有串列的情況。
確認公開金鑰正確
快速使用ssh -vvv ip查看執行詳細過程有無報錯,並根據實際情況進行排查
查看 /var/log/audit/audit.log遠端日誌報錯
檢查遠端目標服/etc/ssh/sshd_config及本地/etc/ssh/ssh_config配置是否正常
嘗試重啟sshd服務
7、開啟sellinux以後ssh需使用密碼登陸。
如下查看檔案的安全上下文:
# ls -laZ .ssh/drwx------ root root ? .dr-xr-x---. root root system_u:object_r:admin_home_t:s0 ..-rw-r--r-- root root ? authorized_keys-rwx------ root root ? id_dsa-rwx------ root root ? id_dsa.pub-rwx------ root root ? id_rsa-rwx------ root root ? id_rsa.pub
如上,我的.ssh目錄檔案的安全上下文跟正常的不配,使用restorecon -r -vv .ssh/ 修複,並將sellinux設定為enforcing,並重啟伺服器以後生效。
修複以後如下:
# ls -laZ .ssh/drwx------. root root system_u:object_r:ssh_home_t:s0 .dr-xr-x---. root root system_u:object_r:admin_home_t:s0 ..-rw-r--r--. root root system_u:object_r:ssh_home_t:s0 authorized_keys-rwx------. root root system_u:object_r:ssh_home_t:s0 id_dsa-rwx------. root root system_u:object_r:ssh_home_t:s0 id_dsa.pub-rwx------. root root system_u:object_r:ssh_home_t:s0 id_rsa-rwx------. root root system_u:object_r:ssh_home_t:s0 id_rsa.pub
如果你發現如上面所顯示的那樣.ssh目錄不是ssh_home_t,使用restorecon -r -vv /home/恢複目錄檔案安全上下文。
這種情況通常是因為我們最初home分區掛載根目錄,未單獨分區,格式化新分區並掛載家目錄以後會導致這樣的問題。
同樣可以使用setenforce 0把SELinux關閉(或修改/etc/selinux/config 檔案重啟生效)
更多關於restorecon ,詳見:http://l.51yip.com/search/restorecon
# getenforce Disabled[[email protected]_bj_10 ~]# setenforce usage: setenforce [ Enforcing | Permissive | 1 | 0 ]
本文出自 “composer” 部落格,請務必保留此出處http://zuoqujia.blog.51cto.com/9151800/1440322
建立linux ssh信任