阿里的服务器默认只有一个root用户,出于安全考虑,服务器到手第一步就应禁止root用户ssh登陆并修改其默认22端口,可添加一个普通用户,使用sudo拥有root权限执行命令,避免直接使用root用户

添加管理权限用户

这里我使用的是ubuntu 22.04系统,首先新建用户:

adduser newuser #改为想要设置的用户名

这时Ubuntu会自动让你输入两次密码,输入密码时不会显示字符,输完回车即可

如没有提示设置密码,可用如下命令设置:

passwd password #改为想要设置的密码

新建用户是没有管理权限的,需要将用户添加到sudo组

adduser newuser sudo

或者直接修改sudoers文件

vim /etc/sudoers
## Allow root to run any commands anywhere
root ALL=(ALL) ALL
newuser ALL=(ALL) ALL #添加新建的用户

BTW,每次使用sudo都要输一次密码,挺烦人的,可以看这篇文章如何取消:【Linux】配置ubuntu sudo指令无需密码

禁止root用户ssh登入

编辑配置文件:

vim /etc/ssh/sshd_config

找到PermitRootLogin yes,将yes改为no

UseDNS no
AddressFamily inet
SyslogFacility AUTHPRIV
PermitRootLogin yes #改为no
PasswordAuthentication yes

保存退出后,重启sshd服务

systemctl restart sshd.service

这时就会发现无法使用root用户登录了。可用普通用户登录,使用sudo su切换至root用户

修改ssh默认端口

编辑配置文件:

vim /etc/ssh/sshd_config

找到Port 22,取消其注释,改为你想要修改的端口号

# The strategy used for options in the default sshd_config shipped with
# OpenSSH is to specify options with their default value where
# possible, but leave them commented.  Uncommented options override the
# default value.

Include /etc/ssh/sshd_config.d/*.conf

#Port 22 #取消注释,改为你想要修改的端口号
#AddressFamily any
#ListenAddress 0.0.0.0
#ListenAddress ::

保存退出后,重启sshd服务

systemctl restart sshd.service

最后记得在防火墙/安全组里放行你修改的端口

安装Fail2ban

文章地址:Fail2ban安装


“但行好事,莫问前程”