-
Notifications
You must be signed in to change notification settings - Fork 0
/
mac_ip_alloc.sh
executable file
·94 lines (76 loc) · 2.39 KB
/
mac_ip_alloc.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#!/usr/bin/env bash
set -e
hostname=$1
ipPrefix=${2:-10.38.}
DHCPConfig=/etc/dnsmasq.d/vm-dhcp.conf
DNSConfig=/etc/dnsmasq.d/vm-dns.conf
(
flock 500
if [ -f ${DHCPConfig} ]; then
ExistedRescord=$(grep -w ${hostname} ${DHCPConfig} || true)
fi
mac1=08
mac2=00
mac3=28
if [ "${ExistedRescord}" != "" ]; then
mac=$(echo ${ExistedRescord} | cut -d "=" -f 2 | awk -F ',' '{ print $1 }')
ip=$(echo ${ExistedRescord} | cut -d "=" -f 2 | awk -F ',' '{ print $3 }')
NextMac4=$(echo ${mac} | awk -F ':' '{ print $4 }')
NextMac5=$(echo ${mac} | awk -F ':' '{ print $5 }')
NextMac6=$(echo ${mac} | awk -F ':' '{ print $6 }')
echo ${mac1}${mac2}${mac3}${NextMac4}${NextMac5}${NextMac6} ${ip}
exit 0
fi
NextMac4=00
NextMac5=00
NextMac6=01
NextIP3=1
NextIP4=1
if [ -f ${DHCPConfig} ]; then
LastRecord=$(tail -1 ${DHCPConfig})
fi
if [ "${LastRecord}" != "" ]; then
LastMac=$(echo ${LastRecord} | cut -d "=" -f 2 | awk -F ',' '{ print $1 }')
LastIP=$(echo ${LastRecord} | cut -d "=" -f 2 | awk -F ',' '{ print $3 }')
if [ "${LastMac}" != "" ]; then
NextMac4=$((16#$(echo ${LastMac} | awk -F ':' '{ print $4 }')))
NextMac5=$((16#$(echo ${LastMac} | awk -F ':' '{ print $5 }')))
NextMac6=$((16#$(echo ${LastMac} | awk -F ':' '{ print $6 }')))
NextMac6=$((${NextMac6} + 1))
if [ ${NextMac6} -ge 16 ]; then
NextMac6=0
NextMac5=$((${NextMac5} + 1))
if [ ${NextMac5} -ge 16 ]; then
NextMac5=0
NextMac4=$((${NextMac4} + 1))
if [ ${NextMac4} -ge 16 ]; then
>&2 echo "More more MAC can be allocated after ${LastMac}"
exit 2
fi
fi
fi
NextMac4=$(printf "%02x\n" ${NextMac4})
NextMac5=$(printf "%02x\n" ${NextMac5})
NextMac6=$(printf "%02x\n" ${NextMac6})
fi
if [ "${LastIP}" != "" ]; then
NextIP3=$(($(echo ${LastIP} | awk -F '.' '{ print $3 }')))
NextIP4=$(($(echo ${LastIP} | awk -F '.' '{ print $4 }')))
NextIP4=$((${NextIP4} + 1))
if [ ${NextIP4} -gt 255 ]; then
NextIP4=0
NextIP3=$((${NextIP3} + 1))
if [ ${NextIP3} -gt 255 ]; then
>&2 echo "More more IP can be allocated after ${LastIP}"
exit 2
fi
fi
fi
fi
ip=${ipPrefix}${NextIP3}.${NextIP4}
echo "dhcp-host=${mac1}:${mac2}:${mac3}:${NextMac4}:${NextMac5}:${NextMac6},${hostname},${ip},infinite" >> ${DHCPConfig}
echo "address=/${hostname}/${ip}" >> ${DNSConfig}
service dnsmasq restart > /dev/null
echo ${mac1}${mac2}${mac3}${NextMac4}${NextMac5}${NextMac6} ${ip}
) 500>/var/lock/mac_ip_alloc
set +e