Skriptimiskeeled aine aruanded 2010 sügis: Difference between revisions

From ICO wiki
Jump to navigationJump to search
Smuuga (talk | contribs)
Smuuga (talk | contribs)
Line 50: Line 50:
Jah, ma tean, et on ka paremaid viise hoste blokeerida, näiteks kasutada hosts-allow parameetrit ssh konfiguratsioonis.
Jah, ma tean, et on ka paremaid viise hoste blokeerida, näiteks kasutada hosts-allow parameetrit ssh konfiguratsioonis.


===Bash versioon===
<source lang="bash">
<source lang="bash">
#!/bin/bash
#!/bin/bash
Line 108: Line 109:
fi
fi
done
done
</source>
===Pythoni versioon===
<source lang="python">
#!/usr/bin/python
# -*- coding: latin-1 -*-
import sys
import getopt
import os
import re
# Skript, mis loeb läbi UNIX-i auth.log faili ja koostab IPTables block reeglid IP aadressidele,
# mille pealt on autentimine ebaõnnestunud vähemalt etteantud arv kordi
# käivitamise näide:
# python check_ip.py /var/log/auth.log /etc/iptables_blocked.txt
# Autor: Sigmar Muuga, DK31
def main():
    # mitme ebaõnnestumise korral me IP blokeerime
    BLOCK_LEVEL=5
   
    def usage():
        print 'Programmi kasutamine:'
        print 'py check_ip.py --logfile=/path/to/logfile --iptablesfile=/path/to/iptablesfile'
       
    def matchCountInFile(str, filename):
        log_file = open(filename, 'r')
        count = 0
        for line in log_file:
            if re.search(str, line):
                count=count+1
        return count
   
    # kontrollime etteantud argumenti
    try:
        opts, args = getopt.getopt(sys.argv[1:], "li:v", ["logfile=", "iptablesfile="])
        AUTH_LOG_FILE = ''
        IP_TABLES_FILE = ''
        for opt, arg in opts:
            if opt == '--logfile':
                AUTH_LOG_FILE = arg
            elif opt == '--iptablesfile':
                IP_TABLES_FILE = arg
        print 'AUTH_LOG_FILE=' + AUTH_LOG_FILE
        print 'IP_TABLES_FILE=' + IP_TABLES_FILE
   
        if AUTH_LOG_FILE.__len__() < 1:
            raise Exception('Invalid auth log filename')
        if IP_TABLES_FILE.__len__() < 1:
            raise Exception('Invalid iptables filename')
        # poolik
       
        if not os.path.isfile(AUTH_LOG_FILE):
            raise Exception('Auth log file does not exist')
       
        ip_pattern = re.compile('([0-9]{1,3}\.){3}[0-9]{1,3}')
       
        log_file = open(AUTH_LOG_FILE, 'r')
        ip_address_array = []
        ip_tables_filehandle = None
        for log_line in log_file:
            if (re.search('error', log_line) != None or re.search('illegal',  log_line) != None or re.search('not allowed', log_line) != None):
                ip_address_match = re.search(ip_pattern, log_line)
                if (ip_address_match == None):
                    continue
                ip_address = ip_address_match.group(0)
                occurences = matchCountInFile(ip_address, AUTH_LOG_FILE)
                if occurences >= BLOCK_LEVEL and not ip_address in ip_address_array:
                    ip_address_array.append(ip_address)
                    print "Blacklisting " + ip_address + " with " + str(occurences) + " occurences"
                    if ip_tables_filehandle == None:
                        ip_tables_filehandle = open(IP_TABLES_FILE, 'w')
                    ip_tables_filehandle.write("iptables -A INPUT -s " + ip_address + " -j DROP\n")
               
        log_file.close()
     
        if (ip_tables_filehandle != None):
            ip_tables_filehandle.close()
    except getopt.GetoptError, err:
        print str(err)
        usage()
        sys.exit(2)
   
if __name__ == "__main__":
    main()
</source>
</source>


==Siim Kullerkupp AK21==
==Siim Kullerkupp AK21==

Revision as of 03:18, 23 January 2011

Siia tulevad kodus tehtud tööde lingid

Esitaja nimi

Vabad ideed

Alvar Unuks AK41

Suurima andmemahuga paketite leidmine

Reget Kalamees DK21

Skript otsib vabade Wifi AP-de hulgast kõige kiirema ühenduse ja haagib end selle külge

Kaspar Prei

Skript leiab dublikaat failid

Lembit Elmik AK21

Skript, mis kontrollib võrguühenduse olemasolu ning selle puudusel diagnoosib häda. V6rgudiagnoosiskript

Marko Valing

Lauri Liibert AK21

Siim Liivand AK41

Midagi mailiserveri logide põhjal?

Sander Tuulik AK41

Skript mis otsib kõik pildi,video,muusika,dokumendid ja jagab need kaustadesse.

Kristjan Karmo AK41

Chris Sinihelm AK41

Nadežda Furs A31

Sigmar Muuga DK31

Skript, mis vaatab /var/log/auth.log faili ja võtab sealt enim ebaõnnestunud IP aadressid, mis üritasid teha sisse logimist SSH kaudu(lävend võiks näiteks olla 10 ebaõnnestunud katset) ning saadab need kas e-mailile või lisab tulemüüri reeglitesse(IPTABLES näiteks).

Jah, ma tean, et on ka paremaid viise hoste blokeerida, näiteks kasutada hosts-allow parameetrit ssh konfiguratsioonis.

Bash versioon

#!/bin/bash

# Skript, mis loeb läbi UNIX-i auth.log faili ja koostab IPTables block reeglid IP aadressidele,
# mille pealt on autentimine ebaõnnestunud vähemalt etteantud arv kordi

# käivitamise näide:
# sh check_ip.sh /var/log/auth.log /etc/iptables_blocked.txt

# Autor: Sigmar Muuga, DK31

# mitme ebaõnnestumise korral me IP blokeerime
BLOCK_LEVEL=5
# auth.log faili asukoht
AUTH_LOG_FILE=$1
# tüüpilised veasituatsioonid
ERROR_PATTERNS="error | illegal | not\ allowed"
# väljundfaili nimi (või asukoht)
IP_TABLES_FILE=$2

# kontrollime etteantud argumenti
if [ -z "$1" ]; then
	echo "No command-line arguments."
	exit 0
fi

if [ -z "$2" ]; then
	echo "No IPTABLES file specified."
	exit 0
fi

# kontrollime, et faili saaks kirjutada
touch "$IP_TABLES_FILE"
if [ -e $IP_TABLES_FILE ]; then
	echo "IPTABLES file: "$IP_TABLES_FILE
else
	echo "Cannot write IPTABLES file!"
	exit 0
fi

# itereerime yle logiridade
more $AUTH_LOG_FILE | egrep "$ERROR_PATTERNS" | while read line; do
	address=$(echo $line | grep -Eo '([0-9]{1,3}\.){3}[0-9]{1,3}')
	# kas on valiidne IP
	if [ ${#address} -gt 0 ]; then
		# loeme esinevuskorrad
		occurences=$(grep -c $address $AUTH_LOG_FILE)
		if [ $occurences -ge $BLOCK_LEVEL ]; then # kui on juba piisavalt feilinud IP
			added_occurences=$(grep -c $address $IP_TABLES_FILE)
			#kontrollime, et poleks juba lisatud
			if [ $added_occurences -lt 1 ]; then
				echo "Blacklisting "$address" with "$occurences" occurences"
				#kirjutame IPTABLES reegli
				echo "iptables -A INPUT -s "$address" -j DROP" >> $IP_TABLES_FILE
			fi
		fi
	fi
done

Pythoni versioon

#!/usr/bin/python
# -*- coding: latin-1 -*-

import sys
import getopt
import os
import re

# Skript, mis loeb läbi UNIX-i auth.log faili ja koostab IPTables block reeglid IP aadressidele,
# mille pealt on autentimine ebaõnnestunud vähemalt etteantud arv kordi
 
# käivitamise näide:
# python check_ip.py /var/log/auth.log /etc/iptables_blocked.txt
 
# Autor: Sigmar Muuga, DK31

def main():
    # mitme ebaõnnestumise korral me IP blokeerime
    BLOCK_LEVEL=5
    
    def usage():
        print 'Programmi kasutamine:'
        print 'py check_ip.py --logfile=/path/to/logfile --iptablesfile=/path/to/iptablesfile'
        
    def matchCountInFile(str, filename):
        log_file = open(filename, 'r')
        count = 0
        for line in log_file:
            if re.search(str, line):
                count=count+1
        return count
    
    # kontrollime etteantud argumenti
    try:
        opts, args = getopt.getopt(sys.argv[1:], "li:v", ["logfile=", "iptablesfile="])
        AUTH_LOG_FILE = ''
        IP_TABLES_FILE = ''
        for opt, arg in opts:
            if opt == '--logfile':
                AUTH_LOG_FILE = arg
            elif opt == '--iptablesfile':
                IP_TABLES_FILE = arg

        print 'AUTH_LOG_FILE=' + AUTH_LOG_FILE
        print 'IP_TABLES_FILE=' + IP_TABLES_FILE
    
        if AUTH_LOG_FILE.__len__() < 1:
            raise Exception('Invalid auth log filename')
        if IP_TABLES_FILE.__len__() < 1:
            raise Exception('Invalid iptables filename')
        # poolik
        
        if not os.path.isfile(AUTH_LOG_FILE):
            raise Exception('Auth log file does not exist')
        
        ip_pattern = re.compile('([0-9]{1,3}\.){3}[0-9]{1,3}')
        
        log_file = open(AUTH_LOG_FILE, 'r')
        ip_address_array = []
        ip_tables_filehandle = None
        for log_line in log_file:
            if (re.search('error', log_line) != None or re.search('illegal',  log_line) != None or re.search('not allowed', log_line) != None):
                ip_address_match = re.search(ip_pattern, log_line)
                if (ip_address_match == None):
                    continue
                ip_address = ip_address_match.group(0)
                occurences = matchCountInFile(ip_address, AUTH_LOG_FILE)
                if occurences >= BLOCK_LEVEL and not ip_address in ip_address_array:
                    ip_address_array.append(ip_address)
                    print "Blacklisting " + ip_address + " with " + str(occurences) + " occurences"
                    if ip_tables_filehandle == None:
                        ip_tables_filehandle = open(IP_TABLES_FILE, 'w')
                    ip_tables_filehandle.write("iptables -A INPUT -s " + ip_address + " -j DROP\n")
                
        log_file.close()
       
        if (ip_tables_filehandle != None):
            ip_tables_filehandle.close()

    except getopt.GetoptError, err:
        print str(err)
        usage()
        sys.exit(2)
    
if __name__ == "__main__":
    main()

Siim Kullerkupp AK21