python从循环中打印第一行

时间:2014-12-28 18:05:47

标签: python linux python-2.7 nmap

我正在尝试从循环中打印第一行。在解析由Nmap生成的XML文件之后生成循环。我不想使用子进程并调用bash命令来执行此操作,但我对如何执行此操作感到难过。它是下面代码中的第二个for循环。

from libnmap.parser import NmapParser

rep = NmapParser.parse_fromfile('Linux_int.xml')

for _host in rep.hosts:
    host = ', '.join(_host.hostnames)
    ip = (_host.address)
    print "HostName: ",host,"--", ip
    #print  _host.os_fingerprinted
host_string  = ip


for osmatch in _host.os.osmatches:
    os = osmatch.name
    accuracy = osmatch.accuracy
    print "Operating System Guess: ", os, "Accuracy Detection", accuracy
    #print os.splitlines()[0:1]


for services in _host.services:
    print services.port, services.protocol, services.state, services.service
    server_address = (host_string,services.port)

这是循环生成的输出。

Operating System Guess:  Linux 3.7 - 3.9 Accuracy Detection 98
Operating System Guess:  Linux 3.8 Accuracy Detection 95
Operating System Guess:  AXIS 210A or 211 Network Camera (Linux 2.6) Accuracy Detection 94
Operating System Guess:  Netgear DG834G WAP or Western Digital WD TV media player Accuracy Detection 94
Operating System Guess:  Linux 3.1 Accuracy Detection 93
Operating System Guess:  Linux 3.2 Accuracy Detection 93
Operating System Guess:  Linux 3.7 Accuracy Detection 92
Operating System Guess:  Linux 3.2.0 Accuracy Detection 91
Operating System Guess:  Linux 3.9 Accuracy Detection 91
Operating System Guess:  Linux 2.6.32 - 3.6 Accuracy Detection 91

这是正在解析的XML文件。

https://www.dropbox.com/s/7me7mxzawmkqj7m/Linux_int.xml?dl=0

2 个答案:

答案 0 :(得分:1)

正如评论中所述,只有break出了循环。如果你对其他行根本不感兴趣。

for osmatch in _host.os.osmatches:
    os_name = osmatch.name
    accuracy = osmatch.accuracy
    print "Operating System Guess: ", os_name, "Accuracy Detection", accuracy
    break

这段代码也可以这样简化:

print "Operating System Guess: ", \
      _host.os.osmatches[0].name, \
      "Accuracy Detection", _\
      host.os.osmatches[0].accuracy

如果_host.os.matches有空的可能性,你可以将它放在try / catch块中。

以下是try / catch,以防您获得IndexError

try:
    print "Operating System Guess: ", \
          _host.os.osmatches[0].name, \
          "Accuracy Detection", _\
          host.os.osmatches[0].accuracy
except IndexError:
    print "No os matches found."

答案 1 :(得分:-2)

print(_host.os.osmatches[0])

基本上会在不破坏循环的情况下做到这一点。你甚至不必使用for循环来打印它。如果它是一个列表元组,它将打印第一个元素。如果它是一个字符串,那么它将打印它的第一个字符。

像:

a="stackover flow"
print (a[0])
>>>
s
>>>

我很惊讶没人写这篇文章。