Skip to content

Instantly share code, notes, and snippets.

@Cgboal
Created November 15, 2020 17:56
Show Gist options
  • Save Cgboal/c22aee81ac9becf8ade52657727f25ef to your computer and use it in GitHub Desktop.
Save Cgboal/c22aee81ac9becf8ade52657727f25ef to your computer and use it in GitHub Desktop.
Common Ports
#!/usr/bin/bb
(defn comment-line? [line]
(re-find #"^\#" line))
(defn tcp-line? [line]
(re-find #"\/tcp" line))
(defn extract-port [substr]
(-> (str substr)
(str/split #"/")
(first)))
(defn str->float [str]
(Float/parseFloat str))
(defn str->int [str]
(Integer/parseInt str))
(defn parse-port-range [port-range]
(map str->int (str/split port-range #"-")))
(def ports-keys [:service :port :incidence])
(def conversions {:service identity
:port extract-port
:incidence str->float})
(defn convert [map-key value]
((get conversions map-key) value))
(defn mapify-ports [rows]
(map (fn [unmapped-row]
(reduce (fn [row-map [port-key value]]
(assoc row-map port-key (convert port-key value)))
{} (map vector ports-keys unmapped-row)))
rows))
(defn filter-garbage-lines [lines]
(->> lines
(filter (complement comment-line?))
(filter tcp-line?)))
(defn build-ports-map []
(let [ports-file-lines (-> (slurp "/usr/share/nmap/nmap-services") (str/split #"\n"))]
(->> ports-file-lines
(filter-garbage-lines)
(map #(str/split % #"\s+"))
(mapify-ports)
(sort-by :incidence >))))
(defn top-n-ports [n ports-map]
(map :port (take n ports-map)))
(defn bottom-n-ports [n ports-map]
(map :port (take-last n ports-map)))
(defn range-ports [[start end] ports-map]
(map :port (subvec (vec ports-map) start end)))
(def actions {:top top-n-ports
:bottom bottom-n-ports
:range range-ports
})
(defn dispatch [ports-map [option val]]
((get actions option) val ports-map))
(def cli-options
[["-t" "--top PORTS" "Top n ports"
:id :top
:parse-fn #(Integer/parseInt %)]
["-b" "--bottom PORTS" "Bottom n ports"
:id :bottom
:parse-fn #(Integer/parseInt %)]
["-r" "--range START-FINISH" "Range of ports from top ports list"
:id :range
:parse-fn parse-port-range]])
(let [args (tools.cli/parse-opts *command-line-args* cli-options)
ports-map (build-ports-map)]
(->>
(dispatch ports-map (first (:options args)))
(str/join ",")
(print)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment