Shell编程面试题6_监控IP连接数,超过100封掉该IP


老男孩出的Shell编程企业面试题6:


写一个脚本解决DOS攻击生产案例
提示:根据web日志或者或者网络连接数,监控当某个IP并发连接数或者短时内PV达到100,即调用防火墙命令封掉对应的IP,监控频率每隔3分钟。防火墙命令为:iptables -I INPUT -s 10.0.1.10 -j DROP。


我的Shell脚本如下:

#!/bin/bash

#environment variable  
source /etc/profile

iplist=`netstat -ntu | awk '{print $5}'| cut -d':' -f1| sort |uniq -c | sed 'N;$d;P;D' | awk '{if($1>100)print $2}'`
for ip in $iplist
do
        iptables -I INPUT -s $ip -j DROP
        echo "$ip is drop!"
done


执行crontab -e,设置每3分钟执行一次:

crontab -e

*/3 * * * * /bin/bash /test/shellstudy/netstatip.sh



  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
可以使用以下的代码实现: ```python import paramiko class SSHClient: def __init__(self, host, port, username, password): self.host = host self.port = port self.username = username self.password = password self.client = paramiko.SSHClient() self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) self.client.connect(self.host, self.port, self.username, self.password) def exec_command(self, command): stdin, stdout, stderr = self.client.exec_command(command) return stdout.readlines() def invoke_shell(self): self.shell = self.client.invoke_shell() return self.shell def send_command(self, command): self.shell.send(command + "\n") while not self.shell.recv_ready(): pass output = self.shell.recv(10000).decode('utf-8') return output def close(self): self.client.close() def ping_ips(ip_list): ssh = SSHClient('your_server_ip', 22, 'your_username', 'your_password') shell = ssh.invoke_shell() shell.recv(1000) shell.send("sudo su\n") shell.recv(1000) shell.send("echo '' > ping_result.txt\n") shell.recv(1000) for ip in ip_list: shell.send("ping -c 1 " + ip + " >> ping_result.txt\n") shell.recv(1000) shell.send("exit\n") ssh.close() with open('ping_result.txt', 'r') as f: result = f.read() return result ``` 这个 `SSHClient` 类可以用来连接远程服务器并执行命令。`invoke_shell()` 方法会返回一个交互式的 shell,此时可以输入命令并获取输出。在这个例子中,我们使用 `sudo su` 命令切换到 root 用户,然后使用 `ping` 命令批量 ping IP,并将结果保存到文件中。最后从文件中读取结果并返回。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

白昼ron

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

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

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

打赏作者

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

抵扣说明:

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

余额充值