记录 Linux Iptables 防火墙 Dropped Packets 日志

最近VPS深受垃圾评论所害,而且IP都是福建莆田的,而且是不停的访问一两个URL!

以下是屏蔽一个IP列表的脚本中的一段,完整的脚本Google一下就出来了。

IPT="/sbin/iptables"
SPAMLIST="blockedip"
SPAMDROPMSG="BLOCKED IP DROP: "

[ -f /root/scripts/blocked.ips.txt ] && BADIPS=$(egrep -v -E "^#|^$" /root/scripts/blocked.ips.txt)

PUB_IF="eth0"

if [ -f /root/scripts/blocked.ips.txt ];
then
# create a new iptables list
$IPT -N $SPAMLIST

for ipblock in $BADIPS
do
$IPT -A $SPAMLIST -s $ipblock -j LOG --log-prefix "$SPAMDROPMSG"
$IPT -A $SPAMLIST -s $ipblock -j DROP
done

$IPT -I INPUT -j $SPAMLIST
$IPT -I OUTPUT -j $SPAMLIST
$IPT -I FORWARD -j $SPAMLIST
fi

This article is part of our ongoing Linux IPTables series of articles. When things are not working as expected with your IPTables rules, you might want to log the IPTables dropped packets for troubleshooting purpose. This article explains how to log both incoming and outgoing dropped firewal packets.

If you are new to IPTables, first get yourself comfortable with the IPTables fundamental concepts.

Log All Dropped Input Packets

First we need to understand how to log all the dropped input packets of iptables to syslog.

If you already have whole bunch of iptables firewall rules, add these at the bottom, which will log all the dropped input packets (incoming) to the /var/log/messages

iptables -N LOGGING
iptables -A INPUT -j LOGGING
iptables -A LOGGING -m limit --limit 2/min -j LOG --log-prefix "IPTables-Dropped: " --log-level 4
iptables -A LOGGING -j DROP

In the above example, it does the following:

  • iptables -N LOGGING: Create a new chain called LOGGING
  • iptables -A INPUT -j LOGGING: All the remaining incoming packets will jump to the LOGGING chain
  • line#3: Log the incoming packets to syslog (/var/log/messages). This line is explained below in detail.
  • iptables -A LOGGING -j DROP: Finally, drop all the packets that came to the LOGGING chain. i.e now it really drops the incoming packets.

In the line#3 above, it has the following options for logging the dropped packets:

  • -m limit: This uses the limit matching module. Using this you can limit the logging using –limit option.
  • –limit 2/min: This indicates the maximum average matching rate for logging. In this example, for the similar packets it will limit logging to 2 per minute. You can also specify 2/second, 2/minute, 2/hour, 2/day. This is helpful when you don’t want to clutter your log messages with repeated messages of the same dropped packets.
  • -j LOG: This indicates that the target for this packet is LOG. i.e write to the log file.
  • –log-prefix “IPTables-Dropped: ” You can specify any log prefix, which will be appended to the log messages that will be written to the /var/log/messages file
  • –log-level 4 This is the standard syslog levels. 4 is warning. You can use number from the range 0 through 7. 0 is emergency and 7 is debug.

Log All Dropped Outgoing Packets

This is same as above, but the 2nd line below has OUTPUT instead of INPUT.

iptables -N LOGGING
iptables -A OUTPUT -j LOGGING
iptables -A LOGGING -m limit --limit 2/min -j LOG --log-prefix "IPTables-Dropped: " --log-level 4
iptables -A LOGGING -j DROP

Log All Dropped Packets (both Incoming and Outgoing)

This is same as before, but we’ll be taking the line number 2 from the previous two examples, and adding it here. i.e We’ll have a separate line for INPUT and OUTPUT which will jump to LOGGING chain.

To log both the incoming and outgoing dropped packets, add the following lines at the bottom of your existing iptables firewall rules.

iptables -N LOGGING
iptables -A INPUT -j LOGGING
iptables -A OUTPUT -j LOGGING
iptables -A LOGGING -m limit --limit 2/min -j LOG --log-prefix "IPTables-Dropped: " --log-level 4
iptables -A LOGGING -j DROP

Also, as we explained earlier, by default, the iptables will use /var/log/messages to log all the message. If you want to change this to your own custom log file add the following line to /etc/syslog.conf

kern.warning /var/log/custom.log

How to read the IPTables Log

The following is a sample of the lines that was logged in the /var/log/messages when an incoming and outgoing packets was dropped.

Aug 4 13:22:40 centos kernel: IPTables-Dropped: IN= OUT=em1 SRC=192.168.1.23 DST=192.168.1.20 LEN=84 TOS=0x00 PREC=0x00 TTL=64 ID=0 DF PROTO=ICMP TYPE=8 CODE=0 ID=59228 SEQ=2
Aug 4 13:23:00 centos kernel: IPTables-Dropped: IN=em1 OUT= MAC=a2:be:d2:ab:11:af:e2:f2:00:00 SRC=192.168.2.115 DST=192.168.1.23 LEN=52 TOS=0x00 PREC=0x00 TTL=127 ID=9434 DF PROTO=TCP SPT=58428 DPT=443 WINDOW=8192 RES=0x00 SYN URGP=0

In the above output:

  • IPTables-Dropped: This is the prefix that we used in our logging by specifying –log-prefix option
  • IN=em1 This indicates the interface that was used for this incoming packets. This will be empty for outgoing packets
  • OUT=em1 This indicates the interface that was used for outgoing packets. This will be empty for incoming packets.
  • SRC= The source ip-address from where the packet originated
  • DST= The destination ip-address where the packets was sent to
  • LEN= Length of the packet
  • PROTO= Indicates the protocol (as you see above, the 1st line is for outgoing ICMP protocol, the 2nd line is for incoming TCP protocol)
  • SPT= Indicates the source port
  • DPT= Indicates the destination port. In the 2nd line above, the destination port is 443. This indicates that the incoming HTTPS packets was dropped

From http://www.thegeekstuff.com/2012/08/iptables-log-packets/

python中的is、==和cmp()比较字符串

python 中的is、==和cmp(),比较字符串

经常写 shell 脚本知道,字符串判断可以用 =,!= 数字的判断是 -eq,-ne 等,但是 Python 确不是这样子地。
所以作为慢慢要转换到用 Python 写脚本,这些基本的东西必须要掌握到骨子里!

在 Python 中比较字符串最好是使用简单逻辑操作符。
例如,确定一个字符串是否和另外一个字符串匹配。正确的,你可以使用 is equal 或 == 操作符。你也可以使用例如 >= 或 < 来确定几个字符串的排列顺序。

从官方文档上看

The operators ``is`` and ``is not`` test for object identity: ``x is
y`` is true if and only if *x* and *y* are the same object.  ``x is
not y`` yields the inverse truth value.

cmp(...)
    cmp(x, y) -> integer

    Return negative if x<y, zero if x==y, positive if x>y.

也就是说 is 用来判断是否是同一个对象,is 是种很特殊的语法,你在其它的语言应该不会见到这样的用法。
python is 主要是判断 2 个变量是否引用的是同一个对象,如果是的话,则返回 true,否则返回 false。
判断数字相等不要用 is 操作符
http://onlypython.group.iteye.com/group/wiki/852-%E6%93%8D%E4%BD%9C%E7%AC%A6is%E7%9A%841%E4%B8%AA%E8%AF%A1%E5%BC%82%E9%97%AE%E9%A2%98

>>> a = 256
>>> b = 256
>>> id(a)
9987148
>>> id(b)
9987148
>>> a = 257
>>> b = 257
>>> id(a)
11662816
>>> id(b)
11662828

为什么两次 is 返回的是不同结果?不是应该都是 true 吗?
因为 string pooling (或叫intern)。 is 相等代表两个对象的 id 相同(从底层来看的话,可以看作引用同一块内存区域)。 至于为什么 “ABC” 被 intern 了而 “a bc” 没有,这是 Python 解析器实现决定的,可能会变。

== 用来判断两个对象的值是否相等(跟 Java 不同,Java 中 == 用来判断是否是同一个对象)。
今天我用 == 来判断两个 IP 地址 字符串是否相同。

#!/usr/bin/python

strtmp = '192.169.1.161'
file_object = open(r'public_ip.txt')
try:
    all_the_text = file_object.readlines()
    firstline = all_the_text[0].rstrip()
finally:
    file_object.close()

#print firstline

#if strtmp == firstline:
s = (strtmp is firstline)
print s
if (strtmp is firstline):
    print 'yes'
else:
    print 'no'

来个简单点的例子:

#-*-conding:utf-8-*-
i='xinwen';
m=input();
if i==m:
    print('yes');
else:
    print('no');

input();

在 if 判断语句中非常有用呐!

#!/usr/bin/python
# Filename: if.py

number = 23
guess = int(raw_input('Enter an integer : '))

if guess == number:
    print 'Congratulations, you guessed it.' # New block starts here
    print "(but you do not win any prizes!)" # New block ends here
elif guess < number:
    print 'No, it is a little higher than that' # Another block
    # You can do whatever you want in a block ...
else:
    print 'No, it is a little lower than that'
    # you must have guess > number to reach here

print 'Done'
# This last statement is always executed, after the if statement is executed

cmp() 函数则是相当于 <,==,> 但是在 Python3 中,cmp() 函数被移除了,所以我以后还是避免少用这个函数。

>>> x='a'
>>> x+'b' is 'ab'
False
>>> x+'b' == 'ab'
True
>>> cmp(x+'b','ab')
0
>>> id(x+'b')
32468384L
>>> id('ab')
46933696L
>>> 

注意:

>>> a='abc'
>>> b='abc'
>>> a is b
True
>>> id(a) == id(b)
True
>>> 

可以看出内容相同的字符串实际上是同一个对象(Java 中直接赋值的字符串也可用 == 来判断,但是使用 new 实例化的对象则需要使用equals(String s) 来判断)。