Bash check if grep matches string -


i writing bash script checks every 5 minutes if there ip address 100 or more invalid passwords (brute force attack) attempts.

the following script works:

blockips="$(cat /var/log/secure | grep "failed password for" | grep -v "invalid" | awk {'print $11'} | sort | uniq -c | awk -v limit=100 '$1 > limit{print $2}')"  while read -r line;  iptables -a input -s $line -p tcp --dport 22 -j drop  echo "blocking ip address: $line" done <<< "$blockips" 

the problem script above after hour have duplicate entries in iptables. tried extend script check if ip address blocked, if so, should skip it.

this script:

blockips="$(cat /var/log/secure | grep "failed password for" | grep -v "invalid" | awk {'print $11'} | sort | uniq -c | awk -v limit=100 '$1 > limit{print $2}')" currentips="$(iptables-save)"  while read -r line;  if grep -q $line $currentips   echo "ip address blocked, skipping"  else  iptables -a input -s $line -p tcp --dport 22 -j drop  echo "blocking ip address: $line"  fi done <<< "$blockips" 

but reasons not working , getting weird output:

grep: 2: no such file or directory grep: 18:19:53: no such file or directory grep: 2015: no such file or directory blocking ip address: 59.47.0.152 grep: #: no such file or directory grep: generated: no such file or directory grep: by: no such file or directory grep: iptables-save: no such file or directory 

what wrong script?

what you're doing is:

grep -q test  string contains word test 

hoping match word in string. grep thinks each of words file, , gives output you're seeing:

grep: this: no such file or directory grep: is: no such file or directory grep: a: no such file or directory grep: string: no such file or directory 

to match in literal string instead of files, send string on stdin:

if grep -q "$line" <<< "$currentips" 

though better off using glob matching:

if [[ "$currentips" = *"$line"* ]] 

note if you've banned 1.2.3.45, 1.2.3.4 match , therefore not banned. can use above approach *" $line "* ensure there spaces around it, if input has that.

also consider installing fail2ban automatically in robust way.


Comments

Popular posts from this blog

python - TypeError: start must be a integer -

c# - DevExpress RepositoryItemComboBox BackColor property ignored -

django - Creating multiple model instances in DRF3 -