-6

in the below code i never seen a syntax like

state=nmScan[tgtHost]['tcp'][int(tgtPort)]['state'] 

this before .looks like multiple list.Can anyone please explain that syntax use case.I never seen any syntax like above in python before.

import nmap
import optparse

def nmapScan(tgtHost,tgtPort):
    nmScan = nmap.PortScanner()
    nmScan.scan(tgtHost,
                tgtPort)
    state=nmScan[tgtHost]['tcp'][int(tgtPort)]['state']
    print "[*] " + tgtHost + " tcp/"+tgtPort +" "+state

def main():
    parser = optparse.OptionParser('-H <10.10.10.104> -p <20-25>')
    parser.add_option('-H', 
                      dest='tgtHost', 
                      type='string', 
                      help='specify target host')
    parser.add_option('-p', 
                      dest='tgtPort', 
                      type='string', 
                      help='specify target port[s] separated by comma')
    (options, args) = parser.parse_args()

    tgtHost = options.tgtHost
    tgtPorts = str(options.tgtPort).split(',')

    if (tgtHost == None) | (tgtPorts[0] == None):
        print parser.usage
        exit(0)

    for tgtPort in tgtPorts:
        nmapScan(tgtHost, tgtPort)


if __name__ == '__main__':
    main()
Spidee
  • 1
  • 3
    Why don't you try `print(nmScan)`, then `print(nmScan[tgtHost])`, then `print(nmScan[tgtHost]['tcp'])` and so on so forth to see what they are? – metatoaster Oct 29 '15 at 01:53
  • 1
    Exact same snippet has come up before [here](http://stackoverflow.com/questions/27516368/inputting-range-of-ports-with-nmap-optparser). It's a port scanner – chucksmash Oct 29 '15 at 01:54
  • 1
    Unrelated, but that `if` statement near the end of `main` is a text-book example of What Not To Write. Don't compare to `None` with `==`, and don't use `|` for logical OR: `if tgtHost is None or tgtPorts[0] is None`. – chepner Oct 29 '15 at 02:17

1 Answers1

1

It's just a series of indexing operations. You could expand it using temporary variables:

t1 = nmScan[tgtHost]
t2 = t1['tcp']
t3 = t2[int(tgtPort)]
state = t3['state']

Since t1 and nmScan[tgtHost] refer the same object, there is no difference between t2 = t1['tcp'] and t2 = nmScan[tgtHost]. The same reasoning holds for longer chaining.

chepner
  • 497,756
  • 71
  • 530
  • 681