Tag Archives: bash

check ip by country linux

yum install geoip
geoipupdate
geoiplookup 1.1.1.1

GeoIP Country Edition: AU, Australia
ipaddr: 1.1.1.1
range_by_ip: 1.1.1.0 – 1.1.1.255
network: 1.1.1.0 – 1.1.1.255 ::24
ipnum: 16843009
range_by_num: 16843008 – 16843263
network num: 16843008 – 16843263 ::24

monitor IP connections per IP

#!/bin/bash
# IP BAN v. 1.0.0

WORK_DIR='/root/ddos'
IGNORE_IP_LIST="$WORK_DIR/ignoreip"
BLOCKED_IP_LIST="$WORK_DIR/blockedip"
LOG_FILE="$WORK_DIR/ban.log"

NO_OF_CONNECTIONS=20
APF_BAN=0
KILL=1

add__cron()
{
set="$(readlink -f "$0")"

if [ ! -f $WORK_DIR/ddos.sh ]; then
# mkdir /root/ddos >/dev/null 2>&1
cp $set $WORK_DIR/ddos.sh
chmod +x $WORK_DIR/ddos.sh
fi
if [ ! -f /etc/cron.d/check_ddos ]; then
echo "* * * * * root $WORK_DIR/ddos.sh >/dev/null 2>&1" > /etc/cron.d/check_ddos
fi

}
mk_ignore()
{
if [ ! -d "$WORK_DIR" ]; then
mkdir $WORK_DIR
fi
if [ ! -f $WORK_DIR/systemip ]; then
ip addr show | grep -w inet | awk '{ print $2 }' | cut -d"/" -f1 > $WORK_DIR/systemip
echo "0.0.0.0" >> $WORK_DIR/systemip
fi

}

prog_check()
{
if ! which netstat >/dev/null; then
apt-get install net-tools
fi
}

prog_check
mk_ignore
add__cron
TMP_PREFIX='/tmp/ddos'
TMP_FILE=`mktemp $TMP_PREFIX.XXXXXXXX`
SYSIP="$WORK_DIR/systemip"

BAD_IP_LIST="$TMP_FILE"
netstat -an | grep -o '[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}' | sort | uniq -c | sort -nr > $BAD_IP_LIST
if [ $KILL -eq 1 ]; then
IP_BAN_NOW=0
while read line; do
CURR_LINE_CONN=$(echo $line | cut -d" " -f1)
CURR_LINE_IP=$(echo $line | cut -d" " -f2)
if [ $CURR_LINE_CONN -lt $NO_OF_CONNECTIONS ]; then
break
fi
IGNORE_BAN=`grep -c $CURR_LINE_IP $IGNORE_IP_LIST`
IGNORE_BAN2=`grep -c $CURR_LINE_IP $SYSIP`
IGNORE_BAN3=`grep -c $CURR_LINE_IP $BLOCKED_IP_LIST`

if [[ $IGNORE_BAN -ge 1 || $IGNORE_BAN2 -ge 1 || $IGNORE_BAN3 -ge 1 ]] ; then
continue
fi
IP_BAN_NOW=1
dt=$(date '+%Y/%m/%d %H:%M:%S');
echo "$CURR_LINE_IP was blocked at $dt" >> $LOG_FILE
echo $CURR_LINE_IP >> $BLOCKED_IP_LIST
if [ $APF_BAN -eq 1 ]; then
$APF -d $CURR_LINE_IP
else
echo $CURR_LINE_IP
/sbin/iptables -I INPUT 1 -s $CURR_LINE_IP -j DROP
/sbin/iptables -I OUTPUT 1 -d $CURR_LINE_IP -j DROP
fi
done < $BAD_IP_LIST fi rm -f $TMP_PREFIX.*

bash rename files for loop

-
rw-rw---- 1 abc mail 47048 Nov 30 13:23 dovecot.index
-rw-rw---- 1 abc mail 800488 Nov 30 15:34 dovecot.index.cache
-rw-rw---- 1 abc mail 28740 Nov 30 15:34 dovecot.index.log
-rw-rw---- 1 abc mail 42928 Nov 30 13:23 dovecot.index.log.2
-rw-rw---- 1 abc mail 72 Sep 25 09:35 dovecot.mailbox.log
-rw-rw---- 1 abc mail 124846 Nov 30 15:34 dovecot-uidlist

hard way (Centos 5):
for i in dove*; do mv -v "$i" "${i%}_old" ; done

simple way:
rename -v 's/$/_old/' dovecot*

-rw-rw---- 1 abc mail 800488 Nov 30 15:34 dovecot.index.cache_old
-rw-rw---- 1 abc mail 42928 Nov 30 13:23 dovecot.index.log.2_old
-rw-rw---- 1 abc mail 28740 Nov 30 15:34 dovecot.index.log_old
-rw-rw---- 1 abc mail 47048 Nov 30 13:23 dovecot.index_old
-rw-rw---- 1 abc mail 72 Sep 25 09:35 dovecot.mailbox.log_old
-rw-rw---- 1 abc mail 124846 Nov 30 15:34 dovecot-uidlist_old

another example extension renaming with for loop:
for f in *.html; do mv $f ${f%.html}.php; done

limit user bash shell with python

Simple use bdsh.py:

#!/usr/bin/python
# Copyright (C) 2013 - Remy van Elst

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program. If not, see .

# This script can act as a shell for a user, allowing specific commands only.
# It tries its best to only allow those comamnds and strip possibly dangerous
# things like ; or >. But it won't protect you if you allow the vim command
# and the user executes !bash via vim (and such). It also logs everything to
# syslog for audit trailing purposes.

# It currently only checks commands, no parameters. This is on purpose.

import getpass, os, re, sys, syslog, signal, socket, readline

# format of whitelist: one command or regex per line
command_whitelist = "/etc/bdsh_whitelist.conf"
username = getpass.getuser()
hostname = socket.gethostname()

def log_command(command, status):
"""Log a command to syslog, either successfull or failed. """
global username
logline_failed = "[RESTRICTED SHELL]: user \"" + username + "\" NOT allowed for " + command
logline_danger = "[RESTRICTED SHELL]: user \"" + username + "\" dangerous characters in " + command
logline_success = "[RESTRICTED SHELL]: user \"" + username + "\" executed " + command
if status == "success":
syslog.syslog(logline_success)
elif status == "failed":
syslog.syslog(logline_failed)
elif status == "danger":
syslog.syslog(logline_danger)

def dangerous_characters_in_command(command):
# via http://www.slac.stanford.edu/slac/www/resource/how-to-use/cgi-rexx/cgi-esc.html
danger = [';', '&', '|', '>', '<', '*', '?', '`', '$', '(', ')', '{', '}', '[', ']', '!', '#'] for dangerous_char in danger: for command_char in command: if command_char == dangerous_char: return True def entire_command_scanner(command): danger = ["&&"] for dangerous_char in danger: if re.findall(dangerous_char, command): return True def execute_command(command): """First log, then execute a command""" log_command(command, "success") # try: # subprocess.call(command, shell=False) # except OSError: # pass os.system(command) def command_allowed(command, whitelist_file=command_whitelist): """Check if a command is allowed on the whitelist.""" try: with open(whitelist_file, mode="r") as whitelist: for line in whitelist: # We are reading commands from a file, therefore we also read the \n. if command + "\n" == line: return True else: continue except IOError as e: sys.exit("Error: %s" % e) def interactive_shell(): global username global hostname while True: prompt = username + "@" + hostname + ":" + os.getcwd() + " $ " try: if sys.version_info[0] == 2: command = raw_input(prompt) else: command = input(prompt) # Catch CRTL+D except EOFError: print("") sys.exit() if command == "exit" or command == "quit": sys.exit() elif command: if not entire_command_scanner(command): if command_allowed(command.split(" ", 1)[0]): for chars in command: if dangerous_characters_in_command(chars): log_command(command, "danger") # Don't let the user know via an interactive shell and don't exit command="" execute_command(command) if __name__ == "__main__": ## Catch CTRL+C / SIGINT. s = signal.signal(signal.SIGINT, signal.SIG_IGN) arguments = "" for args in sys.argv: if dangerous_characters_in_command(args): log_command(args, "danger") sys.exit() ## No Arguments? Then we start an interactive shell. if len(sys.argv) < 2: interactive_shell() else: ## Check if we are not launched via the local shell with a command (./shell.py ls) if sys.argv[1] and sys.argv[1] != "-c" and command_allowed(sys.argv[1].split(" ", 1)[0]) and not entire_command_scanner(sys.argv[1]): for arg in sys.argv[1:]: arguments += arg arguments += " " execute_command(arguments) ## Check if we are launched via the local shell and the command is not allowed elif len(sys.argv) < 3: for arg in sys.argv: arguments += arg arguments += " " log_command(arguments, "failed") elif sys.argv[2] and command_allowed(sys.argv[2].split(" ", 1)[0]) and not entire_command_scanner(sys.argv[2]): for arg in sys.argv[2:]: arguments += arg arguments += " " execute_command(arguments) else: for arg in sys.argv: arguments += arg arguments += " " log_command(arguments, "failed") # Debug use # print("\"" + arguments + "\"") ## Give back the CTRL+C / SIGINT signal.signal(signal.SIGINT, s)

bash bytes coneverter to human

b2h()
{
# By: Simon Sweetwater
# Spotted Script @: http://www.linuxjournal.com/article/9293?page=0,1
# Convert input parameter (number of bytes)
# to Human Readable form
#
SLIST="bytes,KB,MB,GB,TB,PB,EB,ZB,YB"

POWER=1
VAL=$( echo "scale=2; $1 / 1" | bc)
VINT=$( echo $VAL / 1024 | bc )
while [ ! $VINT = "0" ]
do
let POWER=POWER+1
VAL=$( echo "scale=2; $VAL / 1024" | bc)
VINT=$( echo $VAL / 1024 | bc )
done

echo $VAL$( echo $SLIST | cut -f$POWER -d, )
}

k2h()
{
# Convert input parameter (number of kilobytes)
# Spotted Script @: http://www.linuxjournal.com/article/9293?page=0,1
# to Human Readable form
# MODIFIED BY kossboss
SLIST="bytes,KB,MB,GB,TB,PB,EB,ZB,YB"
POWER=1
VAL=$( echo "scale=2; $1 * 1024 / 1" | bc)
VINT=$( echo $VAL / 1024 | bc )
while [ ! $VINT = "0" ]
do
let POWER=POWER+1
VAL=$( echo "scale=2; $VAL / 1024" | bc)
VINT=$( echo $VAL / 1024 | bc )
done
echo $VAL$( echo $SLIST | cut -f$POWER -d, )
}