def ports2nmapspec(portlist):
 portlist = sorted(set(portlist))
 result = []
 current = (None, None)
 for port in portlist:
  if ((port - 1) == current[1]):
   current = (current[0], port)
  else:
   if (current[0] is not None):
    result.append((str(current[0]) if (current[0] == current[1]) else ('%d-%d' % current)))
   current = (port, port)
 if (current[0] is not None):
  result.append((str(current[0]) if (current[0] == current[1]) else ('%d-%d' % current)))
 return ','.join(result)

def ports2nmapspec ( portlist ) : portlist = sorted ( set ( portlist ) ) result = [ ] current = ( None , None ) for port in portlist : if ( ( port - 1 ) == current [ 1 ] ) : current = ( current [ 0 ] , port ) else : if ( current [ 0 ] is not None ) : result . append ( ( str ( current [ 0 ] ) if ( current [ 0 ] == current [ 1 ] ) else ( '%d-%d' % current ) ) ) current = ( port , port ) if ( current [ 0 ] is not None ) : result . append ( ( str ( current [ 0 ] ) if ( current [ 0 ] == current [ 1 ] ) else ( '%d-%d' % current ) ) ) return ',' . join ( result )
this function takes an iterable and returns a string suitable for use as argument for nmaps -p option .