Get public ip for vms
By using kamilas script we can get the ip from a vms mac address.
This commit is contained in:
parent
1ca884e1f6
commit
d13efd4527
1 changed files with 29 additions and 3 deletions
|
@ -1,4 +1,5 @@
|
|||
import oca
|
||||
import ipaddress
|
||||
|
||||
from rest_framework import serializers
|
||||
|
||||
|
@ -81,9 +82,7 @@ class VirtualMachineSerializer(serializers.Serializer):
|
|||
|
||||
|
||||
disk_size = serializers.SerializerMethodField()
|
||||
ip = serializers.CharField(read_only=True,
|
||||
source='user_template.ungleich_public_ip',
|
||||
default='-')
|
||||
ip = serializers.SerializerMethodField()
|
||||
vm_id = serializers.IntegerField(read_only=True, source='id')
|
||||
state = serializers.CharField(read_only=True, source='str_state')
|
||||
price = serializers.SerializerMethodField()
|
||||
|
@ -147,3 +146,30 @@ class VirtualMachineSerializer(serializers.Serializer):
|
|||
template_id = obj.template.template_id
|
||||
template = OpenNebulaManager().get_template(template_id)
|
||||
return template.name
|
||||
|
||||
def get_ip(self, obj):
|
||||
nic = obj.template.nics[0]
|
||||
if is_in_v4_range(nic.mac):
|
||||
return str(v4_from_mac(nic.mac))
|
||||
else:
|
||||
return '-'
|
||||
|
||||
|
||||
|
||||
def hexstr2int(string):
|
||||
return int(string.replace(':', ''), 16)
|
||||
|
||||
FIRST_MAC = hexstr2int('02:00:b3:39:79:4d')
|
||||
FIRST_V4 = ipaddress.ip_address('185.203.112.2')
|
||||
COUNT = 1000
|
||||
|
||||
def v4_from_mac(mac):
|
||||
"""Calculates the IPv4 address from a MAC address.
|
||||
|
||||
mac: string (the colon-separated representation)
|
||||
returns: ipaddress.ip_address object with the v4 address
|
||||
"""
|
||||
return FIRST_V4 + (hexstr2int(mac) - FIRST_MAC)
|
||||
|
||||
def is_in_v4_range(mac):
|
||||
return FIRST_MAC <= hexstr2int(mac) < FIRST_MAC + 1000
|
||||
|
|
Loading…
Reference in a new issue