Shell——如何拿到服务器IP地址

2024-08-16 13:36:43 浏览数 (1)

前言

linux的shell中如何获取服务器的IP地址

内容

代码语言:javascript复制
ip a | grep inet | grep -v inet6 | grep -v 127.0.0.1 | awk '{print $2}'| awk -F "/" '{print $1}'
  1. 我们先ip a 查看IP相关信息
代码语言:javascript复制
[root@tb_scrm_service_kafka_3 bin]# ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN qlen 1
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host
       valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP qlen 1000
    link/ether fa:16:3e:e8:c8:bb brd ff:ff:ff:ff:ff:ff
    inet 192.168.1.86/24 brd 192.168.1.255 scope global noprefixroute dynamic eth0
       valid_lft 70598sec preferred_lft 70598sec
    inet6 fe80::f816:3eff:fee8:c8bb/64 scope link noprefixroute
       valid_lft forever preferred_lft forever
  1. 通过grep来筛选除有用的信息
代码语言:javascript复制
[root@tb_scrm_service_kafka_3 bin]# ip a | grep inet
    inet 127.0.0.1/8 scope host lo
    inet6 ::1/128 scope host
    inet 192.168.1.86/24 brd 192.168.1.255 scope global noprefixroute dynamic eth0
    inet6 fe80::f816:3eff:fee8:c8bb/64 scope link noprefixroute
  1. 通过grep去除无用的信息
代码语言:javascript复制
[root@tb_scrm_service_kafka_3 bin]# ip a | grep inet | grep -v inet6
    inet 127.0.0.1/8 scope host lo
    inet 192.168.1.86/24 brd 192.168.1.255 scope global noprefixroute dynamic eth0
  1. 通过grep,再来一次去除一次无用信息
代码语言:javascript复制
[root@tb_scrm_service_kafka_3 bin]# ip a | grep inet | grep -v inet6 | grep -v '127.0.0.1'
    inet 192.168.1.86/24 brd 192.168.1.255 scope global noprefixroute dynamic eth0
  1. 通过awk打印第二列内容,即IP地址
代码语言:javascript复制
[root@tb_scrm_service_kafka_3 bin]# ip a | grep inet | grep -v inet6 | grep -v '127.0.0.1' | awk '{print $2}'
192.168.1.86/24
  1. 通过awk分割并打印
代码语言:javascript复制
[root@tb_scrm_service_kafka_3 bin]# ip a | grep inet | grep -v inet6 | grep -v '127.0.0.1' | awk '{print $2}' | awk -F '/' '{print $1}'
192.168.1.86

0 人点赞