#!/usr/bin/python2
import requests
import pynetbox
import socket
import subprocess
auth_token = '##'
hed = {'Authorization': 'Token ' + auth_token}
# grab hostname
host = socket.gethostname()
a,b,c = host.split(".")
# create a new device aka server
nb.dcim.devices.create({"name": a, "device_role": 8, "device_type": 1, "site": 1, "rack": 1, "platform": 5})
response = requests.get(url, headers=hed)
data = response.json()
if_id = (data['results'][0]['id'])
#create an interface for the server
nb.dcim.interfaces.create({"name": "eth0", "device": if_id, "form_factor": 800, "mtu": 1400})
response = requests.get(url2, headers=hed)
data2 = response.json()
ip_id = (data2['results'][0]['id'])
print(ip_id)
cmd = "ip -4 -o addr | grep -E '38' | cut -d ' ' -f7 | sed 's/...$//'"
ip,error = subprocess.Popen(cmd, shell=True, executable="/bin/bash", stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
cmd2 = "ip -4 -o addr | grep -E '38' | cut -d ' ' -f7 | cut -d'/' -f2"
net_mask,error = subprocess.Popen(cmd2, shell=True, executable="/bin/bash", stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
ip_format = ip.rstrip() + "/" + net_mask
p = '"{}"'.format(ip_format)
print(p)
nb.ipam.ip_addresses.create(address=ip_format,status=1,interface=ip_id)
# adding ip as main ipv4
device = nb.dcim.devices.get(name=a)
ip = nb.ipam.ip_addresses.get(ip_id)