如何对某个用户配置免密:
ssh-keygen -t rsa -P '' -f ~/.ssh/id_rsa
cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys
chmod 0600 ~/.ssh/authorized_keys
根据上述操作生成相关密钥后,执行ssh localhost,依然需要输入密码,排查问题:
先检查ssh配置文件,包括客户端配置文件ssh_config和服务端配置文件sshd_config
客户端配置文件路径:/etc/ssh/ssh_config
文件内容:
Host *
GSSAPIAuthentication yes
# If this option is set to yes then remote X11 clients will have full access
# to the original X11 display. As virtually no X11 client supports the untrusted
# mode correctly we set this to yes.
ForwardX11Trusted yes
# Send locale-related environment variables
SendEnv LANG LC_CTYPE LC_NUMERIC LC_TIME LC_COLLATE LC_MONETARY LC_MESSAGES
SendEnv LC_PAPER LC_NAME LC_ADDRESS LC_TELEPHONE LC_MEASUREMENT
SendEnv LC_IDENTIFICATION LC_ALL LANGUAGE
SendEnv XMODIFIERS
# 如果是使用dsa生成密钥的话,那么必须要配置上这个参数
PubkeyAcceptedKeyTypes +ssh-dss
服务端配置文件路径:/etc/ssh/sshd_config
文件内容:
HostKey /etc/ssh/ssh_host_rsa_key
#HostKey /etc/ssh/ssh_host_dsa_key
HostKey /etc/ssh/ssh_host_ecdsa_key
HostKey /etc/ssh/ssh_host_ed25519_key
SyslogFacility AUTHPRIV
# Authentication:
# 配置允许root用户登录,yes
# 如果不允许root登录,需要把它改为no
PermitRootLogin yes
AuthorizedKeysFile .ssh/authorized_keys
PasswordAuthentication yes
GSSAPICleanupCredentials no
X11Forwarding yes
UsePrivilegeSeparation sandbox
UseDNS no
# Accept locale-related environment variables
AcceptEnv LANG LC_CTYPE LC_NUMERIC LC_TIME LC_COLLATE LC_MONETARY LC_MESSAGES
AcceptEnv LC_PAPER LC_NAME LC_ADDRESS LC_TELEPHONE LC_MEASUREMENT
AcceptEnv LC_IDENTIFICATION LC_ALL LANGUAGE
AcceptEnv XMODIFIERS
# override default of no subsystems
Subsystem sftp /usr/libexec/openssh/sftp-server
# Example of overriding settings on a per-user basis
#Match User anoncvs
# X11Forwarding no
# AllowTcpForwarding no
# PermitTTY no
# ForceCommand cvs server
KerberosAuthentication no
PubkeyAuthentication yes
UsePAM yes
AuthorizedKeysCommand /usr/bin/sss_ssh_authorizedkeys
AuthorizedKeysCommandUser nobody
GSSAPIAuthentication yes
ChallengeResponseAuthentication yes
# 如果使用dsa生成密钥的话,则必须
PubkeyAcceptedKeyTypes +ssh-dss
KexAlgorithms diffie-hellman-group-exchange-sha1,diffie-hellman-group1-sha1,diffie-hellman-group14-sha1,diffie-hellman-group-exchange-sha256,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521
服务端和客户端按这个配置文件来配是没有问题的,亲测。
PubkeyAcceptedKeyTypes +ssh-dss 是我后加上的参数,但是它并不是之前免密无效的原因,因为我之前生成的密钥使用的是rsa而不是dsa。
所以配置文件这块是没有问题的。
再排查权限问题
首先排查密钥文件authorized_keys的权限,它的权限严格要求是600,因为在步骤1中做了这个操作,所以它的权限是正确的;
接着排查/home/xxx/.ssh目录的权限,它的权限须是700,检查后发现权限是正常的700;
再接着用户主目录的权限,ll /home 查看主目录/home/xxx的权限,发现它的权限是777,然后我把他改小点,改为755,然后再通过ssh localhost测试,这时免密就成功了。
所以之前免密失效的根本原因还是权限的问题,ssh不允许用户的主目录和.ssh目录以及authorized_keys文件的权限开放得太大。