思路:在本地生成公钥和私钥,然后将公钥放到Linux的root(也就是~)目录下的.ssh文件夹下(隐藏文件夹),如何没有则生成一个。
ssh-keygen 用于:生成、管理和转换认证密钥。
常用参数:
-t type:指定要生成的密钥类型,有rsa1(SSH1),dsa(SSH2),ecdsa(SSH2),rsa(SSH2)等类型,较为常用的是rsa类型
-C comment:提供一个新的注释
-b bits:指定要生成的密钥长度 (单位:bit),对于RSA类型的密钥,最小长度768bits,默认长度为2048bits。DSA密钥必须是1024bits
-f filename:指定生成的密钥文件名字
1、 在Mac客户端命令行生成公钥和私钥
cd~/.ssh
ssh-keygen-t rsa-f my_rsa_no_passwd-C"this is discribe you can write any thing"
之后回车两次,注:(Enter passphrase (empty for no passphrase): 可以设置密码),免密做好后首次登录要求输入一次密码,就输入这里的密码。
生成两个文件 my_rsa_no_passwd(私钥)和my_rsa_no_passwd.pub(公钥)
2、 方法一:发送公钥到CentOS服务器端
scp my_rsa_no_passwd.pub user@ip:~/.ssh
如果服务器上没有.ssh文件夹,则登录服务器输入如下命令创建
mkdir~/.ssh
chmod700~/.ssh
3、 登陆CentOS服务器端,设置公钥文件
ssh user@ip#注:此时还是需要输入密码
cd~/.ssh
cat id_rsa.pub>>authorized_keys
chmod600authorized_keys注:必须设置成600
4、 登录来测试下:
ssh -i my_rsa_no_passwd root@ip
就这样子,成功啦。加油!
方法二:
ssh-copy-id-i~/.ssh/id_rsa.pub xiaohua@49.51.1.2-p8888
设置好了居然用不了
二、查看系统安全日志,定位问题
执行 sudo cat /var/log/secure 查看系统的安全日志,然后在安全日志中看到SSH登录过程中提示了如下错误:
Jan1314:20:26VM_0_15_centos polkitd[650]:Operatorof unix-process:4391:118464successfully authenticatedasunix-user:root to gain TEMPORARY authorizationforaction org.freedesktop.login1.rebootforsystem-bus-name::1.85[reboot](ownedbyunix-user:userAAA)
Jan1314:20:26VM_0_15_centos sshd[1277]:Receivedsignal15;terminating.
Jan1314:20:26VM_0_15_centos sshd[4294]:pam_unix(sshd:session):session closedforuser userAAA
Jan1314:21:15VM_0_15_centos polkitd[657]:Loadingrulesfromdirectory/etc/polkit-1/rules.d
Jan1314:21:15VM_0_15_centos polkitd[657]:Loadingrulesfromdirectory/usr/share/polkit-1/rules.d
Jan1314:21:15VM_0_15_centos polkitd[657]:Finishedloading,compilingandexecuting2rules
Jan1314:21:15VM_0_15_centos polkitd[657]:Acquiredthe name org.freedesktop.PolicyKit1on the system bus
Jan1314:21:19VM_0_15_centos sshd[1286]:Serverlistening on0.0.0.0port22.
Jan1314:22:43VM_0_15_centos sshd[1610]:Authenticationrefused:bad ownershipormodesfordirectory/home/userAAA/.ssh
Jan1314:22:55VM_0_15_centos sshd[1610]:AcceptedpasswordforuserAAAfrom11.11.2.161port3236ssh2
Jan1314:22:55VM_0_15_centos sshd[1610]:pam_unix(sshd:session):session openedforuser userAAAby(uid=0)
找到问题:Authentication refused: bad ownership or modes for directory /home/userAAA
后面的目录代表权限不匹配
解决:
chmod g-w/home/userAAA
chmod700./.ssh#关键是这个,权限不能过高
chmod600~/.ssh/authorized_key#关键是这个,权限不能过高