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   mrqiao001  阅读(602)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示