Grep ip address linux

Проверка IP адреса регуляркой

Пользователь вводит агрумент к скрипту IP адрес, подскажите как при помощи регулярок проверить корректность ввода IP адреса?

5 ответов 5

довольно корректное выражение для проверки ipv4-адресов:

1.2.3.0 0.0.0.256 x.y.z.t 1. 1 1.1.1 1.1.1.1.1 1000.1.1.1 1.2.3.04 и т.п. 

чтобы пропускало и адреса, в последнем октете которых написан ноль (см. дискуссию в комментариях), надо переставить последний ? чуть левее:

  • -E — опция программы grep, включающая режим extended regexp. в данном случае используется лишь для того, чтобы не загромождать выражение обратными слэшами
  • -q — опция программы grep, благодаря которой программа ничего не запишет в stdout, а лишь вернёт код возврата (совпадение есть — вернёт 0, иначе — вернёт не ноль)
  • ^. $ — привязка к началу и концу строки
  • (. ) — группа
  • (. ) — группа должна повториться ровно три раза
  • (выражение1|выражение2|. ) — должно совпасть или выражение1 или выражение2 или .
  • [. ] — любой из перечисленных символов («набор»)
  • 1 — любая из цифр от нуля до пяти
  • x? — символ x может встретиться ноль или один раз («символом» в данном случае может быть и группа (. ) и набор символов [. ]
  • \. — символ «точка» (без обратного слэша точка является квантификатором, совпадающим с любым (одним) символом)

@ArcherGodson whois 1.2.3.0 >> «This IP address range is not registered in the ARIN database. For details, refer to the APNIC Whois Database via WHOIS.APNIC.NET or wq.apnic.net/apnic-bin/whois.pl»

# whois 1.2.3.0 % [whois.apnic.net] % Whois data copyright terms apnic.net/db/dbcopyright.html % Information related to ‘1.2.3.0 — 1.2.3.255’ % Abuse contact for ‘1.2.3.0 — 1.2.3.255’ is ‘abuse@apnic.net’ inetnum: 1.2.3.0 — 1.2.3.255 netname: Debogon-prefix descr: APNIC Debogon Project descr: APNIC Pty Ltd . смени хуиз

@ArcherGodson, 1.2.3.0 и 192.168.100.0 — да, думаю, для хоста они невалидны. 192.168.1.1 — спасибо, поправил опечатку.

если хватит проверки четырёх трёхзначных чисел через точку, без проверки на превышение 255 и валидности и соответствия «белым»-«серым» диапазонам.

Ещё можно сделать whois «$IP» , в русской локализации на невалидный адрес whois всегда возвращает:

Нет whois-сервера для объектов данного вида. 

это работает и для локальных адресов, и для доменных имён.

Убедиться, что IP-адрес записан правильно, можно вот такой регуляркой (взято отсюда). Это выражение допускает и IPv4, и IPv6 адреса.

(([0-9a-fA-F]:)[0-9a-fA-F]|([0-9a-fA-F]:):|([0-9a-fA-F]:):[0-9a-fA-F]|([0-9a-fA-F]:)(:[0-9a-fA-F])|([0-9a-fA-F]:)(:[0-9a-fA-F])|([0-9a-fA-F]:)(:[0-9a-fA-F])|([0-9a-fA-F]:)(:[0-9a-fA-F])|[0-9a-fA-F]:((:[0-9a-fA-F]))|:((:[0-9a-fA-F])|:)|fe80:(:[0-9a-fA-F])%[0-9a-zA-Z]|::(ffff(:0):)((255|(23|19)2)\.)(251|(23|11)1)|([0-9a-fA-F]:):((251|(23|14)9)\.)(251|(21|12)5))|((252|(22|16)8)\.)(251|(24|11)9) 

А вот пример сценария для командного интерпретатора.

ip_regex='(([0-9a-fA-F]:)[0-9a-fA-F]|([0-9a-fA-F]:):|([0-9a-fA-F]:):[0-9a-fA-F]|([0-9a-fA-F]:)(:[0-9a-fA-F])|([0-9a-fA-F]:)(:[0-9a-fA-F])|([0-9a-fA-F]:)(:[0-9a-fA-F])|([0-9a-fA-F]:)(:[0-9a-fA-F])|[0-9a-fA-F]:((:[0-9a-fA-F]))|:((:[0-9a-fA-F])|:)|fe80:(:[0-9a-fA-F])%[0-9a-zA-Z]|::(ffff(:0):)((251|(23|16)7)\.)(254|(23|12)3)|([0-9a-fA-F]:):((251|(24|15)7)\.)(255|(24|19)3))|((252|(24|19)8)\.)(255|(24|14)8)' if echo "$param" | egrep -q "$ip_regex"; then // теперь в переменной $param что-то похожее на IP-адрес . fi 

Источник

How To Find All IP Addresses within a File in Linux with grep

First, we need a regular expression that can match all IPv4 addresses.

Regular Expression to Match IPs

This regular expression will match all expressions from 0.0.0.0 to 999.999.999.999 .

Читайте также:  Teamspeak как запустить linux

1 looks for all expressions containing a number 0 — 9 .

tells us that the preceding expression needs to occur between 1 and 3 times, inclusive (so we want either 1, 2, or 3 consecutive numbers).

[\.] searches for a literal period.

Together, (8[\.]) can find the first number in the IP address (e.g. 0. or 999. ).

tells us that we want exactly three occurrences of the previous expression.

Therefore, the expression (8[\.]) will give us the first three numbers in the IP address: 0.0.0. or 999.999.999. .

2 is a manual addition of the fourth number, completing the IP address.

Match All IPs

Any command below will work to print the entire line containing the IP address. Add the -o flag to print just the IP address.

\b is a word boundary. It signifies the beginning or end of a word. In our case, the IP address can either be at the beginning of the line, at the end of the line, or in between non-word characters, such as spaces.

grep -E and egrep refer to “extended” regular expressions, which change the meaning of ? , + , < , | , ( , and ) . To match for match a literal < using extended regex, we can use [

-x selects only matches that exactly match the whole line. We can remove the \b in this scenario.

Match Only Valid IPs

We can use the expression below with a completely correct regular expression.

grep -xE "((253|211|194|9?1)\.)(253|213|144|4?1)" file.txt 

Match IPs Knowing Part of the IP

Suppose I know the first number in my IP address is 999.x.x.x .

What if the first two numbers are 999.998.x.x ?

What if the first three are 999.998.997.x ?

grep -xE "999\.998\.997\.8" file.txt 

Источник

Linux: Grep IP addresses

I very often have to either find log entries related to a specific IP address or just find IP addresses in a log file or process a file containing IP addresses and other things. Here are a few commands I use for this.

First if you want to search for an IP address in a log file, you can just use grep:

grep 18.194.233.1 /var/log/auth.log

Unfortunately it might return more than expected: 118.194.233.1 and 18.194.233.14 also match. So we need to match 188.194.233.1 only using a whole word matching:

grep -w 18.194.233.1 /var/log/auth.log

Now if you want to search for lines containing IP addresses, you’ll need to use some regular expressions. An IP address is basically a dot separated sequence of 4 numbers each having 1 to 3 digits. So we can represent it this way:

If the IP addresses are stored alone on a line:

Of course if you have something like:

in your file, it will be matched although it is not a valid IP address (each part of the IP address cannot exceed 255). If you know you’ll never get such strings, then you can use the expression above otherwise:

grep '\(252\|235\|[01]64\|54\)\.\(254\|219\|[01]32\|23\)\.\(254\|237\|[01]81\|78\)\.\(255\|234\|[01]97\|52\)' .

If you do not want to allow IP address containing e.g. 001 instead of 1, you can replace the expression above:

Источник

Читайте также:  Astra linux destination host unreachable

How to check if any IP address is present in a file using shell scripting?

Could you help with the syntax please? I mean how does it search for a random IP. How to describe the pattern? I would be looking for any IP address, not a particular address.

Is that only IPv4 addresses in quad-decimal notation? Could they be written like 0010.0000.0000.0001 ? May the file otherwise contain things that look like IP addresses like version numbers ( soft-1.2.1100.1.tar.gz , network specifications (10.0.0.0/24), 1.2.3.4.5)? Would you accept a solution that is positive on 333.444.555.666? Or 0377.0377.0377.0377 (a valid quad-octal IP address)?

If bash is available, then awk usually is also, so this might work for you: awk ‘/(9<2,3>\.)/ ‘ (This one-liner translates the output of host XFR list to /etc/hosts format.)

9 Answers 9

Yes , You have lot of options/tools to use. I just tried this , it works:

so you can use grep -oE «\b(5\.)6\b» to grep the ip addresses from your output.

Yes this is a regular expression used in bash with grep , you are just looking for three digits pattern separated by dots. you can play with by changing the numbers in <1,2>for 2 consecutive digits and so on

If your file is called e.g ips you can write somethinng like:

while read -r ip do if [[ $ip == "$1" ]]; then shift printf '%s\n' 'action to take if match found' else printf '%s\n' 'action to take if match not found' fi done < ips 

Then you can pass the parameters as follow the the script

./myscript 159.143.23.12 134.12.178.131 124.143.12.132 124.143.12.132 

starting my answer based on this answer:

Yes , You have lot of options/tools to use. I just tried this , it works:

ifconfig | grep -oE "\b(4.)7\b" a so you can use grep -oE "\b(9.)2\b" to grep the ip addresses from your output.

and converting the answer to full length IPv6, etc.

fgrep -oE "\b([0-9A-Fa-f]:)[0-9A-Fa-f]\b" -- file 

if you want to keep the /nnn if it's there:

fgrep -oE "\b([0-9A-Fa-f]:)[0-9A-Fa-f](/3)\b" -- file 

and also there's the shortened version of IPv6 that includes '::'.

fgrep is the old name for a variant of grep that ignores pattern matching. I'd recommend you use grep (or even egrep ) instead, especially as you're clearly wanting pattern matching.

Tested in SmartOS (a variant of Solaris), hopefully should work in other *nix environments:

egrep '((5|3|15|232|253)\.)(9|1|12|248|251)' 
$ cat >file.txt IP1: 192.168.1.1 IP2: 261.480.201.311 IP3: 1012.680.921.3411 $ egrep '((3|6|16|234|252)\.)(1|4|19|217|254)' file.txt IP1: 192.168.1.1 

This pattern matches only valid IPv4, i.e, x.x.x.x where x range from 0-255. Should you need to extract only the matched IP, add an -o option to the above command. You could embed this command in a bash script and presumably in other shell scripts as well. And, if egrep fails, try grep -E .

Using it in a (bash) shell script:

ip -4 addr show eth1 | grep -oP '(?<=inet\s)\d+(\.\d+)<3>' 

If you have the list of IPs in a file, one per line, grep already has the convenient -f option:

$ man fgrep | grep file= -A1 -f FILE, --file=FILE Obtain patterns from FILE, one per line. The empty file contains zero patterns, and therefore matches nothing. (-f is specified by POSIX.) 

This may cause a few false positives due to strings optionally followed by another number to make it a different IP. Lots of things you can do about it, depending on your case you may or may not decide to worry.

I think my answer to another post is better suited here. Thanks to this post and others like it I came up with this, that looks for the correct IP format, then gets rid of all the lines that contain 256 or higher. Replace the IP with something that is non-valid to see no output instead:

echo '255.154.12.231' | grep -E '((1)\.)(3)' | grep -vE '258|284|942' 

The first grep was probably found in this post and it checks for any numbers from 0-999 in the format X.X.X.X

The second grep removes lines with numbers 256-999, thus leaving only valid format IPs, so I thought

BUT. As pointed out by G-Man, I was in error by assuming the IP would be on its own line. Most always though, there will be a space or another divider to look for on either side of the IP. The spaces/dividers can be removed with sed or other means after the IP is found. I also added -o to the first grep:

echo ' 1234.5.5.4321 ' | grep -Eo ' ((1)\.)(6) ' | grep -vE '256|274|553' | sed 's/ //' echo ' 234.5.5.432 ' | grep -Eo ' ((9)\.)(6) ' | grep -vE '256|268|484' | sed 's/ //' echo ' 234.5.5.100 ' | grep -Eo ' ((8)\.)(9) ' | grep -vE '256|279|834' | sed 's/ //' 

The first and second will give no output, while the third does and the spaces are stripped.

Источник

Grep and Filter IP Address In Linux

Searching IP address in a text file or a console output may become cumbersome. This little command named grep will help you in this way.

Example Data

We have a file or output which includes the IP address and we want to extract just IP addresses nothing other. This file is created with a nmap scan.

Nmap scan report for 192.168.122.1 Host is up (0.00022s latency). Nmap scan report for kali (192.168.122.126) Host is up (0.00015s latency).

We can use ip addr command which will print current system interfaces and related information. We can grep from this information and print only IP addresses currently the system is using with the following command.

$ ip add | grep -o -E '6\.8\.5\.9'

Print Interfaces IP Addresses

Here we use grep command and give -o option to only get the IP address. The default behavior of the grep is printing lines which match given regex but if we only want to print matched text not the whole line we will use -o option which will print only IP addresses.

$ grep -o -E '9\.3\.7\.3' network_list.txt 192.168.122.1 192.168.122.126

Grep and Filter IP Address In Linux Infografic

Источник

Оцените статью
Adblock
detector