Guest User

Untitled

a guest
May 25th, 2018
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.92 KB | None | 0 0
  1. ; my first clojure program -- pings a subnet looking for existing hosts
  2. ; usage (you'll need a clj repl script):
  3. ; clj pingdom.clj 192.168.2
  4. ; clj pingdom.clj --used 10.0.0
  5. ;
  6. (ns pingdom
  7. (:use [clojure.contrib.shell-out :only (sh)])
  8. (:use [clojure.contrib.str-utils :only (re-split str-join)])
  9. (:use [clojure.contrib.string :only (replace-first-re)]))
  10.  
  11. (def *default-subnet* "192.168.1")
  12. (def *ping-cmd* {:mac "ping -c 1 -W 5 -s 1 ",
  13. :nix "ping -c 1 -w 5 -s 1 "})
  14.  
  15. (defn platform []
  16. (let [os-name (System/getProperty "os.name")]
  17. (cond
  18. (.startsWith os-name "Mac") :mac
  19. (or (.startsWith os-name "Linux") (re-find #"nix" os-name)) :nix
  20. :else :other)))
  21.  
  22. (defn ping [ip]
  23. (let [cmd ((platform) *ping-cmd*)
  24. args (re-split #"\s+" (str cmd ip))]
  25. (apply sh args)))
  26.  
  27. (defn host-exists? [ip]
  28. (let [ping-results (ping ip)]
  29. (not (re-find #"100(\.0)?% packet loss" ping-results))))
  30.  
  31. (defn ping-ips [subnet]
  32. (let [subnet-with-dot (replace-first-re #"\.?$" "." subnet)
  33. ips (map #(str subnet-with-dot %) (range 1 255))
  34. futures (map #(future {:ip %, :exists (host-exists? %)}) ips)]
  35. (map deref (doall futures))))
  36.  
  37. (defn available-ips [subnet]
  38. (map :ip (remove :exists (ping-ips subnet))))
  39.  
  40. (defn used-ips [subnet]
  41. (map :ip (filter :exists (ping-ips subnet))))
  42.  
  43. (defn get-subnet-from-args [args default]
  44. (or
  45. (first (filter #(re-find #"^\d" %) args))
  46. default))
  47.  
  48. (defn get-options-from-args [args]
  49. (filter #(re-find #"^\-" %) args))
  50.  
  51. (defn options-include? [options & args]
  52. (some #((set options) %) options))
  53.  
  54. (let [args *command-line-args*
  55. subnet (get-subnet-from-args args *default-subnet*)
  56. options (get-options-from-args args)]
  57. (if (options-include? options "-u" "--used")
  58. (println (str "Used IPs:\n"
  59. (str-join "\n" (used-ips subnet))))
  60. (println (str "Available IPs\n"
  61. (str-join "\n" (available-ips subnet))))))
  62.  
  63. (shutdown-agents)
Add Comment
Please, Sign In to add comment