Linux服务器密钥安全登录
使用密钥登录的好处:1、省事,不用每次去敲用户名和密码;2、安全,密钥长度一般是1024位,比我们设的密码要长得多;
以下是为新用户jackson添加密钥登录的步骤。
1、添加用户,并添加到sudoer。
useradd jackson passwd jackson
添加到sudo组
visudo
在 root ALL=(ALL) ALL 后添加 hubery ALL=(ALL) ALL
2、生成并添加公钥到Server
ssh-keygen -t rsa ssh-copy-id -i ~/.ssh/id_rsa.pub -p [port] user@server
如果当前用户不能ssh登陆(已经关闭了密码登录的情况),则可以
#local scp -P [port] id_rsa.pub user1@server:/home/user1/ ssh user1@server -p [port] su user2 cd ~ mkdir .ssh chmod 700 .ssh cd .ssh touch authorized_keys chmod 600 authorized_keys sudo cat /home/user1/id_rsa.pub > authorized_keys
注意~/.ssh和~/.ssh/authorized_keys的权限。
本地添加私钥
vim ~/.ssh/config
添加以下内容
#iksdbsrvice 2 Host 192.168.0.122 IdentityFile ~/.ssh/id_rsa
注意,Host前没有空格,IdentifyFile前为一个tab
3、修改ssh配置文件,路径为/etc/ssh/sshd_config,去注释或修改一下内容
# Port 22000 # PermitRootLogin no # RSAAuthentication yes PubkeyAuthentication yes AuthorizedKeysFile .ssh/authorized_keys PermitEmptyPasswords yes PasswordAuthentication no UsePAM no X11Forwarding yes
以上部分修改了sshd的端口,禁止了root用户的远程登陆,开启了密钥登录,禁止了密码登录。对于多个服务器的管理,我是直接替换的文件,这样简单且保持了一致性。
//local scp -P [port] sshd_config user@server:/your/home/ //server sudo cp ~/sshd_config /etc/ssh/sshd_config
4、iptables设置
sudo iptables -I INPUT 1 -p tcp --dport 22000-j ACCEPT sudo service iptables save
5、重启sshd服务,测试登录
sudo service sshd restart
ssh user@server -p [port]
6、ssh登录时响应慢
常见的原因是因为server的sshd会去DNS查找访问client IP的hostname,如果DNS不可用或者没有相关记录,就会耗费大量时间。在server上/etc/ssh/sshd_config文件中修改或加入 UseDNS=no,另外在authentication gssapi-with-mic也有可能出现问题,在server上/etc/ssh/sshd_config文件中修改 GSSAPIAuthentication no。
注意:在没有测试通过之前,不要关闭之前打开的终端,这样即使是改错了,也是可以用这个终端改回来的。