utils.py 文件源码

python
阅读 23 收藏 0 点赞 0 评论 0

项目:AerisCloud 作者: AerisCloud 项目源码 文件源码
def local_ip():
    """
    Retrieve the first ip from the interface linked to the default route

    :return str
    """
    sys_name = system()
    if sys_name == 'Darwin':
        # OSX
        route = Command('route')
        ifconfig = Command('ifconfig')

        iface = [
            line.strip()
            for line in route('-n', 'get', 'default')
            if line.strip().startswith('interface')
        ][0].split(':')[1].strip()
        return [
            line.strip()
            for line in ifconfig(iface)
            if line.strip().startswith('inet ')
        ][0].split(' ')[1]
    elif sys_name == 'Linux':
        try:
            ip = Command('ip')
            iface = [
                line.strip()
                for line in ip('route')
                if line.strip().startswith('default ')
            ][0].split(' ')[4]
        except CommandNotFound:
            route = Command('route')
            iface = [
                line.strip()
                for line in route('-n')
                if line.startswith('0.0.0.0')
            ][0].split(' ').pop()

        try:
            # try with IP
            ip = Command('ip')
            return [
                line.strip()
                for line in ip('addr', 'show', iface)
                if line.strip().startswith('inet ')
            ][0].split(' ')[1].split('/')[0]
        except CommandNotFound:
            pass

        # fallback to ifconfig
        ifconfig = Command('ifconfig')
        return [
            line.strip()
            for line in ifconfig(iface)
            if line.strip().startswith('inet ')
        ][0].split(' ')[1]

    return None
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号