-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathDBIP-Calc.py
273 lines (250 loc) · 8.08 KB
/
DBIP-Calc.py
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
# Import libraries
import sys
import requests
import json
import os
import string
import pymysql
# End imports
def DotDecGen (iDecValue):
if iDecValue < 1 or iDecValue > 4294967295:
return "Invalid"
# end if
# Convert decimal to hex
HexValue = hex(iDecValue)
#Ensure the results is 8 hex digits long.
#IP's lower than 16.0.0.0 have trailing 0's that get trimmed off by hex function
HexValue = "0"*8+HexValue[2:]
HexValue = "0x"+HexValue[-8:]
# Convert Hex to dot dec
strTemp = str(int(HexValue[2:4],16)) + "." + str(int(HexValue[4:6],16)) + "."
strTemp = strTemp + str(int(HexValue[6:8],16)) + "." + str(int(HexValue[8:10],16))
return strTemp
def DotDec2Int (strValue):
strHex = ""
if ValidateIP(strValue) == False:
return 0
# end if
Quads = strValue.split(".")
for Q in Quads:
QuadHex = hex(int(Q))
strwp = "00"+ QuadHex[2:]
strHex = strHex + strwp[-2:]
# next
return int(strHex,16)
def ValidateIP(strToCheck):
Quads = strToCheck.split(".")
if len(Quads) != 4:
return False
# end if
for Q in Quads:
try:
iQuad = int(Q)
except ValueError:
return False
# end try
if iQuad > 255 or iQuad < 0:
return False
# end if
return True
def IPCalc (strIPAddress):
strIPAddress=strIPAddress.strip()
strIPAddress=strIPAddress.replace("\t"," ")
strIPAddress=strIPAddress.replace(" "," ")
strIPAddress=strIPAddress.replace(" /","/")
dictIPInfo={}
iBitMask=0
if "/" in strIPAddress:
IPAddrParts = strIPAddress.split("/")
strIPAddress=IPAddrParts[0]
try:
iBitMask=int(IPAddrParts[1])
except ValueError:
iBitMask=32
# end try
else:
iBitMask = 32
# end if
if ValidateIP(strIPAddress):
dictIPInfo['IPAddr'] = strIPAddress
dictIPInfo['BitMask'] = str(iBitMask)
iHostcount = 2**(32 - iBitMask)
dictIPInfo['Hostcount'] = iHostcount
iDecIPAddr = DotDec2Int(strIPAddress)
dictIPInfo['DecIP'] = iDecIPAddr
iDecSubID = iDecIPAddr-(iDecIPAddr%iHostcount)
iDecBroad = iDecSubID + iHostcount - 1
dictIPInfo['iDecSubID'] = iDecSubID
dictIPInfo['iDecBroad'] = iDecBroad
dictIPInfo['Subnet'] = DotDecGen(iDecSubID)
dictIPInfo['Broadcast'] = DotDecGen(iDecBroad)
else:
dictIPInfo['IPError'] = "'" + strIPAddress + "' is not a valid IP!"
# End if
return dictIPInfo
def SQLConn (strServer,strDBUser,strDBPWD,strInitialDB):
try:
# Open database connection
return pymysql.connect(host=strServer,user=strDBUser,password=strDBPWD,db=strInitialDB)
except pymysql.err.InternalError as err:
print ("Error: unable to connect: {}".format(err))
sys.exit(5)
except pymysql.err.OperationalError as err:
print ("Operational Error: unable to connect: {}".format(err))
sys.exit(5)
except pymysql.err.ProgrammingError as err:
print ("Programing Error: unable to connect: {}".format(err))
sys.exit(5)
def SQLQuery (strSQL,db):
try:
# prepare a cursor object using cursor() method
dbCursor = db.cursor()
# Execute the SQL command
dbCursor.execute(strSQL)
# Count rows
iRowCount = dbCursor.rowcount
if strSQL[:6].lower() == "select":
dbResults = dbCursor.fetchall()
else:
db.commit()
dbResults = ()
return [iRowCount,dbResults]
except pymysql.err.InternalError as err:
if strSQL[:6].lower() != "select":
db.rollback()
return "Internal Error: unable to execute: {}".format(err)
except pymysql.err.ProgrammingError as err:
if strSQL[:6].lower() != "select":
db.rollback()
return "Programing Error: unable to execute: {}".format(err)
except pymysql.err.OperationalError as err:
if strSQL[:6].lower() != "select":
db.rollback()
return "Programing Error: unable to execute: {}".format(err)
except pymysql.err.IntegrityError as err:
if strSQL[:6].lower() != "select":
db.rollback()
return "Integrity Error: unable to execute: {}".format(err)
def ValidReturn(lsttest):
if isinstance(lsttest,list):
if len(lsttest) == 2:
if isinstance(lsttest[0],int) and isinstance(lsttest[1],tuple):
return True
else:
return False
else:
return False
else:
return False
def FindMask(iDecSubID,iDecBroad):
strIPAddress = DotDecGen(iDecSubID)
for x in range(1,32):
strSubnet = "{}/{}".format(strIPAddress,x)
dictIPInfo = IPCalc (strSubnet)
# print (dictIPInfo)
# print ("iDecBroad 1:{}".format(iDecBroad))
# print ("iDecBroad 2:{}".format(dictIPInfo['iDecBroad']))
if iDecBroad == dictIPInfo['iDecBroad']:
return strSubnet
if iDecBroad < dictIPInfo['iDecBroad']:
return "Partial match:{}".format(strSubnet)
return "{}/{}".format(strIPAddress,32)
iLoc = sys.argv[0].rfind(".")
strConf_File = sys.argv[0][:iLoc] + ".ini"
strLine = " "
print ("Reading in configuration")
objINIFile = open(strConf_File,"r")
strLines = objINIFile.readlines()
objINIFile.close()
for strLine in strLines:
iCommentLoc = strLine.find("#")
if iCommentLoc > -1:
strLine = strLine[:iCommentLoc].strip()
else:
strLine = strLine.strip()
if "=" in strLine:
strConfParts = strLine.split("=")
strVarName = strConfParts[0].strip()
strValue = strConfParts[1].strip()
if strVarName == "Server":
strServer = strValue
if strVarName == "dbUser":
strDBUser = strValue
if strVarName == "dbPWD":
strDBPWD = strValue
if strVarName == "InitialDB":
strInitialDB = strValue
if strVarName == "TableName":
strTableName = strValue
if strVarName == "RecordID":
strRecordID = strValue
if strVarName == "IPField":
strIPField = strValue
if strVarName == "NetID":
strNetIDField = strValue
if strVarName == "BroadCast":
strBroadCastField = strValue
if strVarName == "IntIPAddr":
strIntIPField = strValue
if strVarName == "HostCount":
strHostCountField = strValue
if strVarName == "BitMask":
strBitMaskField = strValue
dbConn = SQLConn (strServer,strDBUser,strDBPWD,strInitialDB)
strSQL = ("SELECT {},{} FROM {}.{};".format(strRecordID,strIPField,strInitialDB,strTableName))
lstSubnets = SQLQuery (strSQL,dbConn)
iRowCount = lstSubnets[0]
if not ValidReturn(lstSubnets):
print ("Unexpected: {}".format(lstSubnets))
sys.exit(8)
else:
print ("Fetched {} rows".format(lstSubnets[0]))
if lstSubnets[0] == 0:
print ("Nothing to do, exiting")
sys.exit(9)
iRowNum = 1
for dbRow in lstSubnets[1]:
strSubnet = dbRow[1]
iSubnetID = dbRow[0]
dictIPInfo = IPCalc (strSubnet)
if "iDecSubID" in dictIPInfo:
iDecSubID = dictIPInfo['iDecSubID']
else:
iDecSubID = -10
if "iDecBroad" in dictIPInfo:
iDecBroad = dictIPInfo['iDecBroad']
else:
iDecBroad = -10
if "Hostcount" in dictIPInfo:
iHostcount = dictIPInfo['Hostcount']
else:
iHostcount = -10
if "DecIP" in dictIPInfo:
iDecIP = dictIPInfo['DecIP']
else:
iDecIP = -10
if "BitMask" in dictIPInfo:
iBitMask = dictIPInfo['BitMask']
else:
iBitMask = -10
if "IPError" in dictIPInfo:
print (dictIPInfo['IPError'])
if iDecSubID > 0:
strSubnet = FindMask(iDecSubID,iDecBroad)
iRowNum += 1
print ("Completed {:.1%}".format(iRowNum/iRowCount),end="\r")
print(".", end="")
strSQL = ("UPDATE {db}.{table} SET {NetIDField} = {NetIDValue}, {BroadcastField} = {BroadcastValue},"
" {iIPField} = {iIPValue}, {HostCountField} = {HostCountValue},"
" {BitMaskField} = {BitMaskValue} WHERE {IDField} = {IDValue};".format(
NetIDValue=iDecSubID, BroadcastValue=iDecBroad, HostCountValue=iHostcount,
IDValue=iSubnetID, db=strInitialDB, table=strTableName, NetIDField=strNetIDField,
BroadcastField=strBroadCastField, iIPField=strIntIPField, IDField=strRecordID,
HostCountField=strHostCountField, BitMaskField=strBitMaskField, BitMaskValue=iBitMask,
iIPValue=iDecIP))
lstReturn = SQLQuery (strSQL,dbConn)
if not ValidReturn(lstReturn):
print ("Unexpected: {}".format(lstReturn))
break
# elif lstReturn[0] != 1:
# print ("{} \n Records affected {}, expected 1 record affected".format(strSQL, lstReturn[0]))