linux系统过滤ip地址总结

Perl模块用法
安装Perl模块
# 官网地址 https://metacpan.org/pod/Regexp::Common
# 下载地址 https://cpan.metacpan.org/authors/id/A/AB/ABIGAIL/Regexp-Common-2017060201.tar.gz
安装步骤
wget https://cpan.metacpan.org/authors/id/A/AB/ABIGAIL/Regexp-Common-2017060201.tar.gz
tar xf Regexp-Common-2017060201.tar.gz
cd Regexp-Common-2017060201/
perl Makefile.PL 
make
# apt/yum install make -y
make install

 # 过滤IPv6
ip a |perl -MRegexp::Common=net  -lnE 'say $& if /$RE{net}{MAC}/g'

 # 过滤IPv4
ip a |perl -MRegexp::Common=net  -lnE 'say $& if /$RE{net}{IPv4}/g'

 # 过滤MAC地址
ip a |perl -MRegexp::Common=net  -lnE 'say $& if /$RE{net}{IPv6}/g'
IPv4过滤常规方法

# 1、正则匹配过滤
ifconfig | awk '/inet / && $6 ~ /[0-9]/{print$2}'
ifconfig | grep -Po 'inet \K(?!127\.)\d{1,3}.\d{1,3}\.\d{1,3}\.\d{1,3}'
ip a | grep -oE "\b([0-9]{1,3}\.){3}[0-9]{1,3}\b"
ip a | sed -nr 's#.*inet ([^ ]+)\/.*#\1#p'
ip a | awk '$1=="inet"{split($2,a,"/");print a[1]}'  # awk split用法

# 2、按照段落读取
ifconfig | awk 'BEGIN{RS=""}{print $6}'

# 3、注意:多块网卡时,需要排除lo网卡,因为eth0顺序不能保证在第一段
ifconfig | awk 'BEGIN{RS="";FS="\n"}!/^lo:/{$0=$2;FS=" ";$0=$0;print $2;FS="\n"};'

# 4、其他获取IPv4的用法
ifconfig | grep "inet "|awk '{print $2}'
ip -4 -o a | awk '{split($4,a,"/");print a[1]}'
ip -br address | awk '{print substr($3,1,index($3,"/")-1);}'

 # 5、过滤网卡名称
ls -l /sys/class/net | awk '/devices/{print $(NF-2)}'
ifconfig | grep  "mtu" |awk -F": " '{print $1}'
eth0
lo
wg0

# 6、过滤物理网卡
ls -l /sys/class/net | awk '$NF~/pci0/ { print $(NF-2); exit }'


# 获取公网IP
curl -4 icanhazip.com 
curl http://ifconfig.me/ip
wget http://ipecho.net/plain -O - -q
wget -qO - icanhazip.com

# 添加获取本机IP地址的快捷命令
echo "alias myip=\"ifconfig | sed -En 's/127.0.0.1//;s/.*inet (addr:)?(([0-9]*\.){3}[0-9]*).*/\2/p'\"">>/root/.bashrc 
==>myip

posted on 2022-12-13 23:29  mrqiao001  阅读(592)  评论(0编辑  收藏  举报