Extract ip address from string variable

I am trying to create a bash script that will be able to change the "allow from" ip address in the phpmyadmin command file (which they still have not been able to do) and restart apache

I'm currently trying to extract the ip address from a variable and after searching the internet I still don’t know, that’s what I still have ...

#bash shell script
#!/bin/bash

clear
echo "Get client IP address"
ip=$(last -i)
echo $ip

exit
echo "restart apache"
/etc/init.d/apache2 reload

I tried adding the following line with no luck

ip=$(head -n 1 $ip)

If someone tells me how I can extract the first instance of an IP address from $ ip variables, I would really appreciate it.

+4
source share
8 answers
ip=$(last -i | head -n 1 | awk '{print $3}')

Update:

ip=$(last -i | grep -Pom 1 '[0-9.]{7,15}')
+6
source

You can use grepwith read:

read ip < <(last -i | grep -o '[0-9]\+[.][0-9]\+[.][0-9]\+[.][0-9]\+')
read ip < <(last -i | grep -Eo '[0-9]+[.][0-9]+[.][0-9]+[.][0-9]+')
  • \bmay also be helpful. Just not sure about its compatibility.

:

ip=$(last -i | gawk 'BEGIN { RS = "[ \t\n]"; FS = "." } /^([0-9]+[.]){3}[0-9]+$/ && ! rshift(or(or($1, $2), or($3, $4)), 8) { print ; exit; }')
+6

, :

ip=$(last -i -1 | awk '{print $3}')
+2

ip=$($ last -i -1 | grep -Po '(\d+\.){3}\d+')

grep , Perl, \d . [0-9], (, , 123.45.123), . -o grep .

, ( , , system boot ). GNU grep, , , @konsolebox.

+2

bash:

read -ra array < <(last -i)
ip="${array[2]}"

:

read -ra array < <(last -1 -i)
ip="${array[2]}"
0

, nitpicker ( grep -P), :

while read -r testline
do
    echo "input :=$testline="
    read ip < <(grep -oP '\b(?:(?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2})[.](?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2})[.](?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2})[.](?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2}))\b' <<< "$testline")
    echo "result:=${ip:=NOTFOUND}="
    echo
done <<EOF
some bla bla 127.0.0.1 some
10.10.10.10
bad one 300.200.300.400
some other bla 127.0.0.1 some another 10.1.1.0
10.10.10.10 10.1.1.0
bad one 300.200.300.400 and good 192.168.1.1

above is empty and no ip here too
EOF

ip adr, 800.1.1.1, :

input :=some bla bla 127.0.0.1 some=
result:=127.0.0.1=

input :=10.10.10.10=
result:=10.10.10.10=

input :=bad one 300.200.300.400=
result:=NOTFOUND=

input :=some other bla 127.0.0.1 some another 10.1.1.0=
result:=127.0.0.1=

input :=10.10.10.10 10.1.1.0=
result:=10.10.10.10=

input :=bad one 300.200.300.400 and good 192.168.1.1=
result:=192.168.1.1=

input :==
result:=NOTFOUND=

input :=above is empty and no ip here too=
result:=NOTFOUND=

\b ip, : 610.10.10.10, , ip (10.10.10.10).

: https://metacpan.org/pod/Regexp::Common::net

0

, , - , , IP- (v4), , 4 1-3 3 '.

# Basic Regular Expression to loosly match an IP address:
bre_match_ip="[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}"

# Extended Regular Expression to loosly match an IP address:
ere_match_ip="[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}"

, IP (v4) (, HTML) URL-, . Awk, Bash script ( ) IP- . , URL-, , IP .

I appreciate that this is too much for the original poster and that it is not intended for its needs, but someone who searches can come up with this answer and find the rather comprehensive nature of the code. The Awk code is fortunately well-commented as it uses some slightly obscure aspects of Awk that may not be familiar to the average Awk user.

awkExtractIPAddresses='
BEGIN {
    # Regex to match an IP address like sequence (even if too long to be an IP).
    # This is deliberately a loose match, the END section will check for IP
    # address validity.
    ipLikeSequence = "[0-9]+[.][0-9]+[.][0-9]+[.][0-9]+[0-9.]*";

    # Regex to match a number sequence longer than 3 digits.
    digitSequenceTooLongNotIP = "[0-9][0-9][0-9][0-9]+";

    # Regex to match an IP address like sequence which is a version number.
    # Equivalent to "(version|ver|v)[ .:]*" if "tolower($0)" was used.
    versioningNotIP = "[Vv]([Ee][Rr]([Ss][Ii][Oo][Nn])?)?[ .:]*" ipLikeSequence;

    # Regexes to match IP address like sequences next to forward slashes, to
    # avoid version numbers in urls: e.g. http://web.com/libs/1.6.1.0/file.js
    beginsWithFwdSlashNotIP = "[/]" ipLikeSequence;
    endsWithFwdSlashNotIP = ipLikeSequence "[/]";
}
{
    # Set line to the current line (more efficient than using $0 below).
    line = $0;

    # Replace sequences on line which will interfere with extracting genuine
    # IPs. Use a replacement char and not the empty string to avoid accidentally
    # creating a valid IP address from digits on either side of the removed
    # sections. Use "/" as the replacement char for the 2 "FwdSlash" regexes so
    # that multiple number dot slash sequences all get removed, as using "x"
    # could result in inadvertently leaving such a sequence in place.
    # e.g. "/lib1.6.1.0/1.2.3.4/5.6.7.8/file.js" leaves "/lib1.6.1.0xx/file.js"

    gsub(digitSequenceTooLongNotIP, "x", line);
    gsub(versioningNotIP, "x", line);
    gsub(beginsWithFwdSlashNotIP, "/", line);
    gsub(endsWithFwdSlashNotIP, "/", line);

    # Loop through the current line matching IP address like sequences and
    # storing them in the index of the array ipUniqueMatches. By using ipMatch
    # as the array index duplicates are avoided and the values can be easily
    # retrieved by the for loop in the END section. match() automatically sets
    # the built in variables RSTART and RLENGTH.

    while (match(line, ipLikeSequence))
    {
        ipMatch = substr(line, RSTART, RLENGTH);
        ipUniqueMatches[ipMatch];
        line = substr(line, RSTART + RLENGTH + 1);
    }
}
END {
    # Define some IP address related constants.
    ipRangeMin = 0;
    ipRangeMax = 255;
    ipNumSegments = 4;
    ipDelimiter = ".";

    # Loop through the ipUniqueMatches array and print any valid IP addresses.
    # The awk "for each" type of loop is different from the norm. It provides
    # the indexes of the array and NOT the values of the array elements which
    # is more usual in this type of loop.

    for (ipMatch in ipUniqueMatches)
    {
        numSegments = split(ipMatch, ipSegments, ipDelimiter);
        if (numSegments == ipNumSegments &&
            ipSegments[1] >= ipRangeMin && ipSegments[1] <= ipRangeMax &&
            ipSegments[2] >= ipRangeMin && ipSegments[2] <= ipRangeMax &&
            ipSegments[3] >= ipRangeMin && ipSegments[3] <= ipRangeMax &&
            ipSegments[4] >= ipRangeMin && ipSegments[4] <= ipRangeMax)
        {
            print ipMatch;
        }
    }
}'

# Extract valid IP addresses from $fileName, they will each be separated
# by a new line.
awkValidIpAddresses=$(awk "$awkExtractIPAddresses" < "$fileName")

I hope this is of interest.

0
source

You can use awk.

ip=$(awk '{if(NR == 1) {print $3; exit;}}' < <(last -i))
0
source

All Articles