linux ssh限制IP登录

        写个shell来限制其他IP的人登录自己团队的机器。

        shell脚本内容:

offline.sh:

       

#!/usr/bin/env sh                                                                                                                                                                                                                                                                               
# only using for root user to offline ip address

if [ "$(whoami)" != "root" ]
then
        printf "execute rule is not root!\nwhoami:[%s]\nexit!\n" "$(whoami)"
        exit
fi

ip_list_file="/home/user/ip_list"
log_file="offline.log"

while true
do
        sleep 2
        # get ip list string
        grep_list=""
        if [ ! -f "${ip_list_file}" ]
        then
                echo "$(date +%Y-%m-%d\ %H:%M:%S)       ${ip_list_file} is not exist!" >> "${log_file}"
                continue
        fi
        while read Line
        do
                if expr "${Line}" : "^[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\$" > /dev/null
                then
                        echo $Line
                        grep_list="${grep_list}|${Line}:"
                fi
        done<"${ip_list_file}"
        grep_list=${grep_list:1}
        grep_list_len=${#grep_list}
        if [ ${grep_list_len} -le 10 ]
        then
                echo "$(date +%Y-%m-%d\ %H:%M:%S)       ip list is empty! not need offline!" >> "${log_file}"
                continue
        fi

        printf "$(date +%Y-%m-%d\ %H:%M:%S)     ip list[%s]\n" "${grep_list}" >> "${log_file}"


        lsof -i :22|awk '{print $9"\t"$2}'|grep "\->"|awk -F"->" '{print $2}'|while read Line
        do
                echo "${Line}"|grep -vE "${grep_list}"|awk '{print $2}' | xargs -i sh -c "kill -9 {} && echo \"$(date +%Y-%m-%d\ %H:%M:%S)      inet:[${Line}]    kill process success\" >> \"${log_file}\""
        done
done
          用于存放允许进入本机器IP的文件

ip_list:

10.45.50.168
10.45.50.164
[luo.xxxxxx]
10.45.48.183
10.45.48.186
[liu.xxxxxx]
10.45.48.162


备注:

offline.sh需要用root用户权限启动。

如果IP改变了:

1.先登录固定IP,且被一直执行offline.sh这台机器允许登录的机器,再ssh登录到这个offline.sh机器上修改ip_list文件

2.用expect编写远程登录kill这个offline.sh的脚本。

spawn ssh "${usr}@${ip}" "ps -ef|grep offline|grep -v grep|sed -e s#\\\\\s\\\\\+#\\\\\t#g|cut -f 2|xargs -i -t kill -9 {}"
expect {
    "*assword*" {
        send "${pwd}\r"
        interact
    }
    timeout {
        send_user "timeout,exit!"
        exit 1
    }
    eof {
        send_user "eof, exit!"
        exit 1
    }
}



其实ssh本来就允许设置IP,只让这部分IP登录。

       

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值