ssh连接踢出脚本

ssh连接踢出脚本

踢出脚本

[root@ubuntu24-13:~]# cat /etc/profile.d/kick_if_remote.sh
#!/bin/bash

# 获取登录 IP(排除本地登录)
login_ip=$(who | grep -m1 "$USER" | awk '{print $5}' | tr -d '()')

# 若为空,认为是本地控制台登录
[ -z "$login_ip" ] && exit 0

# 查询 IP 所在地区(用 ip-api 免费接口)
geo=$(curl -s --connect-timeout 2 "http://ip-api.com/json/${login_ip}?lang=zh-CN")

# 提取国家、省份、城市
country=$(echo "$geo" | grep '"country"' | cut -d '"' -f4)
region=$(echo "$geo" | grep '"regionName"' | cut -d '"' -f4)
city=$(echo "$geo" | grep '"city"' | cut -d '"' -f4)

# 设置允许的省市白名单
ALLOW_REGIONS=("Beijing" "Shanghai" "Guangdong")
ALLOW_CITIES=("Beijing" "Shanghai" "Guangzhou" "Shenzhen")

# 检查是否在白名单中
is_allowed_region=false
is_allowed_city=false

for r in "${ALLOW_REGIONS[@]}"; do
  if [[ "$region" == "$r" ]]; then
    is_allowed_region=true
    break
  fi
done

for c in "${ALLOW_CITIES[@]}"; do
  if [[ "$city" == "$c" ]]; then
    is_allowed_city=true
    break
  fi
done

# 如果省和市任一不符合,就踢掉连接
if [[ "$is_allowed_region" != "true" || "$is_allowed_city" != "true" ]]; then
  echo "你的IP ${login_ip} 来自 ${country}-${region}-${city},不在允许区域,连接已被拒绝!"
  sleep 1
  pkill -KILL -t $(who am i | awk '{print $2}')
fi
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

良辰美景好时光

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值