获取服务器内网地址

# A类:10.0.0.0 - 10.255.255.255
# B类:172.16.0.0 - 172.31.255.255
# C类:192.168.0.0 - 192.168.255.255

import subprocess


def get_inner_ip():
    # CentOS 6 or CentOS 7 or CentOS 8
    cmd = "cat /etc/redhat-release"
    p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    res = p.communicate()[0]

    if res.startswith("CentOS release 6"):
        prefix_str = "ifconfig | grep inet | %s | head -1 | awk '{print $2}' | awk -F: '{print $2}'"
    else:
        prefix_str = "ifconfig | grep inet | %s | head -1 | awk '{print $2}'"

    grep_v_string = "grep -v 127.0.0.1"

    while True:
        get_inner_ip_cmd = prefix_str % grep_v_string

        p = subprocess.Popen(get_inner_ip_cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

        inner_ip = p.communicate()[0].split('\n')[0]

        if inner_ip == '':
            return False

        temp_list = inner_ip.split('.')
        if not inner_ip.startswith('192.168.') and \
                not inner_ip.startswith('10.') and \
                (not int(temp_list[0]) == 172 and not 16 <= int(temp_list[1]) <= 31):
            grep_v_string += " | grep -v %s" % inner_ip
            continue

        break

    return inner_ip

 

posted @ 2020-04-28 20:41  道霖  阅读(609)  评论(0编辑  收藏  举报