写个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登录。