更新于 

SSH 配置与使用

SSH 配置文件路径
/etc/ssh/sshd_config

1
2
#重启 SSH
service sshd restart

修改 SSH 端口

修改/etc/ssh/sshd_config配置文件中 Port 字段

如果开启了防火墙,防火墙需要放行对应端口

1
2
3
# semanage port -a -t ssh_port_t -p tcp #PORTNUMBER
# Port 22
#AddressFamily any

禁止 root 用户远程登录

修改/etc/ssh/sshd_config文件
找到如下代码

1
2
3
#LoginGraceTime 2m
#PermitRootLogin yes
#StrictModes yes

去掉 PermitRootLogin no 的注释并 把 yes 修改为 no

SSH 登录邮箱提醒

安装 jq,实现获取登录地:

1
sudo yum install -y jq

确保 OpenSSH 使用PAM,查看/etc/ssh/sshd_config:设置UsePAM的值为yes

使用 pam_exec 为 OpenSSH 注册动作:

1
vi /etc/pam.d/sshd

在最后一行添加:

1
session optional pam_exec.so seteuid /etc/ssh/login-notifications.sh

创建login-notifications.sh脚本用于邮件发送:

1
vi /etc/ssh/login-notifications.sh

填写如下内容:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#!/bin/sh
export LANG=en_US.UTF-8
if [ "$PAM_TYPE" = "open_session" ]
then
address="$(curl --connect-timeout 2 -s http://ip-api.com/json/{$PAM_RHOST}?lang=zh-CN | jq -r '. as {country:$country, city:$city}|$country+$city')"
{
echo "User: $PAM_USER"
echo "Remote Host: $PAM_RHOST"
echo "Address: $address"
echo "Service: $PAM_SERVICE"
echo "TTY: $PAM_TTY"
echo "Date: `date "+%Y-%m-%d %H:%M:%S"`"
echo "Server: `uname -a`"
} | mail -s "[SSH Login]$PAM_SERVICE login on `hostname -s` for account $PAM_USER" receiver@email.com #接收邮件的邮箱
fi
exit 0

为脚本赋予可执行权限:

1
chmod +x /etc/ssh/login-notifications.sh