如果使用nmap时Statement无法正常工作

时间:2019-01-16 17:25:46

标签: python if-statement nmap

我在获取if语句正常工作时遇到了一些麻烦。 iplist.txt的末尾有一个我不想运行的空行,但是由于某种原因,它仍在运行。我尝试删除文件的最后一行,但它仅删除最后一个合法行,而不是空白行,我什至尝试删除空格,空行和空行,但仍然可以运行一行。最奇怪的是,空白同时在if块和else块中运行。

 with open ("iplist.txt", "r") as file:
     filecontents = file.read()
     for line in filecontents.split('\n'):
      filename = (line) + ".txt "
      command = "nmap -O -oG " + ".\\ips\\" + (filename) + (line)
      print(command)
      print(filename)
      strlen = int (len(filename))
      print(strlen)
      compareline = line[:4]
      print(compareline)
      if compareline == beginline: #beginline is declared as 10.9 earlier in the file
       print("Testing 1..2...")
       os.system(command)
       filenameforos = (line + ".txt")
       #detailedosdetection = open(filenameforos)
       #next(filecontents)
      else:
       print("Testing...")
       del line
       #next(StopIteration)

这是iplist.txt的内容

10.9.10.38
10.9.10.45
10.9.11.10
#extra line
编辑

我尝试过,但是没有运行循环,我确定我做错了。

with open ("iplist.txt", "r") as file:
 filecontents = file.read()
 lines = file.readlines()
 lines = [x.strip() for x in lines]
 print("Creating list")
 for line in lines:
  filename = (line) + ".txt "
  command = "nmap -O -oG " + ".\\ips\\" + (filename) + (line)
  print(command)
  print(filename)
  strlen = int (len(filename))
  print(strlen)
  compareline = line[:4]
  print(compareline)
  if compareline == beginline: #beginline is declared as 10.9 earlier in the file
   print("Testing 1..2...")
   os.system(command)
   filenameforos = (line + ".txt")
   #detailedosdetection = open(filenameforos)
   #next(filecontents)
  else:
   print("Testing...")
   del line
   #next(StopIteration)

1 个答案:

答案 0 :(得分:0)

Python有一种读取单独行的方法。试试

lines = file.readlines()
lines = [x.strip() for x in lines] #To remove unneccesary white spaces and "\n"

而不是在“ \ n”上拆分文件