CentOS,将ipV6转换为long to long form

时间:2016-04-19 04:44:25

标签: bash centos ipv6

我刚刚开始使用bash脚本,但是我需要解决一个小问题:

我以这种格式获取IPv6地址: 1080::8:800:200C:417A

现在我想将短片转换为长的IPv6形式,如:1080:0:0:0:8:800:200C:417A

是否有正则表达式或类似的东西转换它?

我正在使用在CentOS上运行的docker容器。

3 个答案:

答案 0 :(得分:3)

它不是一个正则表达式,但它是类似的'它完成了这项工作:(用python3.5.1测试)

>>> import ipaddress
>>> x = '1080::8:800:200C:417A'
>>> y = ipaddress.ip_address(x)
>>> y.exploded
'1080:0000:0000:0000:0008:0800:200c:417a'
>>> 

参考: https://docs.python.org/3/library/ipaddress.html

答案 1 :(得分:1)

#!/bin/bash
echo "enter the ip address:"
read s
if [[ $s =~ ^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$ ]]; then

        echo -e '\E[47;31m'"\033[1mIPv6 Format\033[0m" 
        echo -n "The IPv6 Address Expanded Form:"
        EXPANDED=`sipcalc $s | fgrep Expand | cut -d '-' -f 2`
        echo -e "\033[32m $EXPANDED\033[0m"
        echo -n "IPv6 address Compress Form:"
        Compress=`sipcalc $s | fgrep Comp | cut -d '-' -f 2`
        echo  -e "\033[32m$Compress\033[0m"
        echo -n "Address Type of IPv6:"
        type=`sipcalc $s | fgrep type | cut -d '-'  -f 2,3,4`
        comment=`sipcalc $s | fgrep Comment | cut -d '-' -f 2`
        echo -e "\033[32m $type$comment\033[0m"
else
        echo  -e '\E[37;44m'"\033[1mNOT VALID IPv6 address\033[0m"
fi

这是我的ipv6验证代码.U将使用" sipcalc"来获取扩展形式的ip。但是你应该做一些grep和cut命令

答案 2 :(得分:0)

这是我解压缩IPv6地址的方式。

#!/bin/bash

decompress_ipv6_address() {
    # How many hextets are there
    num_hextets=${addr//[^:]/}
    num_hextets=${#num_hextets}

    # Fix up beginning and end
    [[ $addr =~ ^:: ]] && addr='0'$addr
    [[ $addr =~ ::$ ]] && addr=$addr'0'

    # Create additional hextets
    additional_hextets=':'
    for (( i=$num_hextets; $i<8; i++ ))
    do
        additional_hextets=$additional_hextets'0:'
    done

    # Insert additional hextets (replace ::)
    addr=${addr/::/$additional_hextets}
}