开发者

Extracting ip address from auth.log line to a variable

I am going nuts here already, but I need to extract ip address from such line:

"Jan 15 14:05:57 seerrrver sshd[9784]: User root from 218.108.249.44 not allowed because not listed in AllowUsers"

I think, it should be something like this: address=$(expr match "$line" '\b[[:digit:]]{1,3}.[[:digit:]]{1,3}.[[:digit:]]{1,3}.[[:digit:]]{1,3}\b')

开发者_开发百科

But actually these regular expressions doesnt work with expr match command. I have tried this match with other command and it works, the only place, where it doesnt work, is the expr match command.


Grep is made for cases like this.

address=$(echo "Jan 15 14:05:57 seerrrver sshd[9784]: User root from 218.108.249.44 not allowed because not listed in AllowUsers" | grep -Eo '([0-9]{1,3}\.){3}[0-9]{1,3}')

echo $address returns the IP address.

Assuming you have a full log file, it makes sense to process all rows at once and put the output in an array:

addressarray=( $(cat logfile | grep -Eo '([0-9]{1,3}\.){3}[0-9]{1,3}' |  sed -n -e ":a" -e "$ s/\n/ /gp;N;b a") )

You can look at the contents of the array using echo ${addressarray[@]} or access its values by replacing the @ with an index number (starting with 0). echo ${addressarray[0]} would give you the first address.

Use this to iterate over the array values: for i in ${!addressarray[@]}; do echo ${addressarray[$i]}; done


There's no need to use expr since Bash 3.2 and later have regex matching.

string="Jan 15 14:05:57 seerrrver sshd[9784]: User root from 218.108.249.44 not allowed because not listed in AllowUsers"
pattern='\<([0-9]{1,3}\.){3}[0-9]{1,3}\>'
[[ $string =~ $pattern ]]
address=${BASH_REMATCH[0]}

The regex support provided by expr is very limited (it only does basic regular expressions - BRE) rather than extended ones (ERE)).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜