1、生成本地服务器ssh私钥,如已存在,可忽略。
$ssh-keygen-trsaGeneratingpublic/privatersakeypair.Enterfileinwhichtosavethekey(/root/.ssh/id_rsa):
一路回车,会在本地家目录~/.ssh/生成密钥文件,检查如果存在,则可忽略。(更多ssh-keygen使用帮助,见ssh-keygen -h)
生成以后,如下:
$ls-ltra~/.ssh/id_rsa*-rw-r–r–.1rootroot408May413:20/root/.ssh/id_rsa.pub-rw——-.1rootroot1675May413:20/root/.ssh/id_rsa
2、ssh登陆远端服务器,开通防火墙,如已开通,可忽略
$/sbin/iptables-IINPUT-ieth0-s10.10.10.10-ptcp-mtcp–dports22-jACCEPT
开通防火墙以后,确认本地ssh 10.10.10.11 22能通(假设本地服务器IP:10.10.10.10,远端服务器IP为:10.10.10.11)
3、确认远端服务器存在~/.ssh/authorized_keys文件及对应目录,不存在则创建、否者可忽略。
$ls-ltra~/|grepsshdrwx——.2rootroot4096May413:38.ssh$ls-ltr.ssh/authorized_keys-rw——-.1rootroot408May413: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.pub10.10.10.11$ssh-copy-id-hUsage:/usr/bin/ssh-copy-id[-i[identity_file]][user@]machine
完成以后,正常情况下,我们就可以本地无密码直接ssh登陆远端服务器了。
如将本地用户luser公钥内容追加到远端用户ruser家目录~/.ssh/authorized_keys文件中,那么本地用户就可以sshruser@10.10.10.11(远端ip),需要访问用户的对应关系一定要搞清楚了。
6、非正常情况,我们会遇到一些错误,即使按照上面的步骤做完了以后,依然无法无密码登陆。
7、开启sellinux以后ssh需使用密码登陆。
如下查看文件的安全上下文:
#ls-laZ.ssh/drwx——rootroot?.dr-xr-x—.rootrootsystem_u:object_r:admin_home_t:s0..-rw-r–r–rootroot?authorized_keys-rwx——rootroot?id_dsa-rwx——rootroot?id_dsa.pub-rwx——rootroot?id_rsa-rwx——rootroot?id_rsa.pub
如上,我的.ssh目录文件的安全上下文跟正常的不配,使用restorecon -r -vv .ssh/ 修复,并将sellinux设置为enforcing,并重启服务器以后生效。
修复以后如下:
#ls-laZ.ssh/drwx——.rootrootsystem_u:object_r:ssh_home_t:s0.dr-xr-x—.rootrootsystem_u:object_r:admin_home_t:s0..-rw-r–r–.rootrootsystem_u:object_r:ssh_home_t:s0authorized_keys-rwx——.rootrootsystem_u:object_r:ssh_home_t:s0id_dsa-rwx——.rootrootsystem_u:object_r:ssh_home_t:s0id_dsa.pub-rwx——.rootrootsystem_u:object_r:ssh_home_t:s0id_rsa-rwx——.rootrootsystem_u:object_r:ssh_home_t:s0id_rsa.pub
#getenforceDisabled[root@dbbak_bj_10~]#setenforceusage:setenforce[Enforcing|Permissive|1|0]
更多关于restorecon,详见:
本文出自 “composer” 博客,请务必保留此出处
回避现实的人,未来将更不理想。