Geçenlerde bir Web Servisinden ilgili IP aralığını çekip IP bloklarını hesaplamak ihtiyacı doğdu. Aşağıdaki kod bloğu ilgili web servisine yetkili kullanıcı ile giriş yaptıktan sonra, IP aralıklarını çekmekte ve bazı hesaplamalardan sonra IP bloklarını hesaplamaktadır. Ardından hesaplanan IP blokları bir dosyaya yazılmaktadır.
#!/usr/bin/env python
from suds.client import Client
from suds.wsse import *
import ipaddress
apnlist_file_name = 'APNblocks'
url = "http://abc.com/spgw/services/AuthenticationPort?wsdl"
url2 = "http://abc.com/view/ApnListService.wsdl"
#get sessionId
client = Client(url)
sessionid = client.service.createSession('admin','password')
#get APN List
token = {'sessionId' : sessionid }
client2 = Client(url2)
ssnns = ('ssn','http://abc.com/mapping/generated')
ssn = Element('sessionId', ns=ssnns).setText(sessionid)
client2.set_options(soapheaders=(token,ssn))
result = client2.service.ApnList("wap")
begin_ip_last_value = []
end_ip_last_value = []
begin_ip_third_value = []
end_ip_third_value = []
begin_ip_second_value = []
end_ip_second_value = []
begin_ip_first_value = []
end_ip_first_value = []
cidr_last = []
cidr_third = []
#empty file
open(apnlist_file_name, 'w').close()
for i in range(0,len(result["blockList"]["block"])):
ipBlockBegin = result["blockList"]["block"][i]["ipBlockBegin"]
ipBlockEnd = result["blockList"]["block"][i]["ipBlockEnd"]
begin_ip_last_value.append(int(ipBlockBegin.split('.')[3]))
end_ip_last_value.append(int(ipBlockEnd.split('.')[3]))
begin_ip_third_value.append(int(ipBlockBegin.split('.')[2]))
end_ip_third_value.append(int(ipBlockEnd.split('.')[2]))
begin_ip_second_value.append(int(ipBlockBegin.split('.')[1]))
end_ip_second_value.append(int(ipBlockEnd.split('.')[1]))
begin_ip_first_value.append(int(ipBlockBegin.split('.')[0]))
end_ip_first_value.append(int(ipBlockEnd.split('.')[0]))
if begin_ip_third_value[i] == 0:
cidr_third = 255 - end_ip_third_value[i]
elif begin_ip_third_value[i] == 128:
cidr_third = 128
elif begin_ip_third_value[i] == end_ip_third_value[i]:
cidr_third = 255
else:
cidr_third = end_ip_third_value[i] - begin_ip_third_value[i]
if begin_ip_last_value[i] == 1:
cidr_last = 0
else:
cidr_last = 255 - (begin_ip_last_value[i] - 1)
cidr_last = 255 - cidr_last
if (begin_ip_last_value[i] == end_ip_last_value[i]) & (begin_ip_third_value[i] == end_ip_third_value[i]):
continue
cidr = "255.255." + str(cidr_third) + '.' + str(cidr_last)
ipBlockBegin = str(begin_ip_first_value[i]) + '.' + str(begin_ip_second_value[i]) + '.' + str(begin_ip_third_value[i]) + '.' + str(0)
result_with_network = ipaddress.ip_network(u'%s/%s' % (ipBlockBegin, cidr))
netmask = result_with_network.prefixlen
ipBlock = str(begin_ip_first_value[i]) + '.' + str(begin_ip_second_value[i]) + '.' + str(begin_ip_third_value[i]) + '.'+ str(begin_ip_last_value[i] - 1) + '/' + str(netmask) + '\n'
file = open(apnlist_file_name,'a')
file.write(ipBlock)