2017-04-10 65 views
-1

我有,我想自动执行以下程序,分配IP地址遵循这些准则某些系统的特定池: 1.跳过前10级的IP 2.填充IP地址每个子网- Python脚本跳过行

我使用Python 3.5.1 我可是从CSV文件工作,这里是一个数据我一起工作的样品:

  • 网络堆栈等系统单位
  • 10.0.28.0 CAB_DS4-2_2
  • 10.0.28.32 CAB_DS4-2_2
  • 10.0.28.64 CAB_DS4-1_1
  • 10.0.28.96 CAB_DS4-1_2
  • 10.0.28.128 CAB_DS3-2_1
  • 10.0.28.160 CAB_DS3-3_1
  • 10.0.28.192 CAB_DS3 -3_2
  • 10.0.28.224 CAB_DS2-2_1

这里是我做的代码,它适用于数据正好一半,从8个子网,它只有4个分配的。下面是代码:

import csv 
import ipaddress 

with open('sorted2.csv') as csv_file: 
    ip_pool = csv.reader(csv_file) 
    next(ip_pool) 

    for row in ip_pool: 
     ip = ipaddress.ip_address(row[0]) 
     nextROW = next(ip_pool) 
     ip_end = nextROW[0] #NEXT network limit 
     counter = 0 

     ip_end = ipaddress.ip_address(ip_end) 
     ip_next = ip + 9 # skip first 10 IPs 
     ip_assign = ipaddress.ip_address(ip_next) 

     print ('NEW NET:', ip) 
     while ipaddress.ip_address(ip_assign) < ipaddress.ip_address(ip_end)-1: 
      counter += 1 # count number of IPs assigned, to be implemented later 
      ip_assign = ipaddress.ip_address(ip_assign)+1 #iterate next IP 
      ip_start = ip_assign 

      print(ip_assign) 
     ip_next = ip_assign 

这里是代码的输出:

NEW NET: 10.0.28.0 
10.0.28.10 
10.0.28.11 
10.0.28.12 
10.0.28.13 
10.0.28.14 
10.0.28.15 
10.0.28.16 
10.0.28.17 
10.0.28.18 
10.0.28.19 
10.0.28.20 
10.0.28.21 
10.0.28.22 
10.0.28.23 
10.0.28.24 
10.0.28.25 
10.0.28.26 
10.0.28.27 
10.0.28.28 
10.0.28.29 
10.0.28.30 
10.0.28.31 
NEW NET: 10.0.28.64 
10.0.28.74 
10.0.28.75 
10.0.28.76 
10.0.28.77 
10.0.28.78 
10.0.28.79 
10.0.28.80 
10.0.28.81 
10.0.28.82 
10.0.28.83 
10.0.28.84 
10.0.28.85 
10.0.28.86 
10.0.28.87 
10.0.28.88 
10.0.28.89 
10.0.28.90 
10.0.28.91 
10.0.28.92 
10.0.28.93 
10.0.28.94 
10.0.28.95 
NEW NET: 10.0.28.128 
10.0.28.138 
10.0.28.139 
10.0.28.140 
10.0.28.141 
10.0.28.142 
10.0.28.143 
10.0.28.144 
10.0.28.145 
10.0.28.146 
10.0.28.147 
10.0.28.148 
10.0.28.149 
10.0.28.150 
10.0.28.151 
10.0.28.152 
10.0.28.153 
10.0.28.154 
10.0.28.155 
10.0.28.156 
10.0.28.157 
10.0.28.158 
10.0.28.159 
NEW NET: 10.0.28.192 
10.0.28.202 
10.0.28.203 
10.0.28.204 
10.0.28.205 
10.0.28.206 
10.0.28.207 
10.0.28.208 
10.0.28.209 
10.0.28.210 
10.0.28.211 
10.0.28.212 
10.0.28.213 
10.0.28.214 
10.0.28.215 
10.0.28.216 
10.0.28.217 
10.0.28.218 
10.0.28.219 
10.0.28.220 
10.0.28.221 
10.0.28.222 
10.0.28.223 

正如你所看到的,它跳过子网4,我似乎无法把我的手指上有什么我编码错误/忘记了。任何帮助非常感谢

+1

通过调用'next(ip_pool)'来修改'ip_pool'' –

回答

0

在迭代它时,您不应该修改ip_pool

相反迭代行并试图获得,而迭代接下来,跟踪上一行的(我们仍然可以将其命名row)的,但是我们的迭代将取代当前排过的下一行,:

row = next(ip_pool) 
for nextROW in ip_pool: 
    ... 
    row = nextROW 
+0

好吧我理解你的意思只是不知道如何实现你在我的代码暗示的修复程序 – user7421969

+0

我不是当然还有什么可以解释的。在循环开始时,将其替换为我发布的循环开始。在循环结尾添加'row = nextROW'行。 '...'应该保持不变,尽管你应该删除'nextROW = next(ip_pool)'这一行,因为'nextROW'的值已经被处理了。 –

+0

非常感谢。 – user7421969