Ruby nmap script to scan IP range for wireless camera and push IP to web server
When our son was born, my wife and I purchased and setup an IP camera in his room. Unfortunately its IP changes periodically and it can be annoying to look it up. I finally gave in and wrote a network IP scan script to find its IP, and copy it to a file on my server in a public location.
First I used Homebrew to install nmap on my Mac:
brew install nmap
nmap is a great tool for ip scanning. It provides an option “-O” to look up a system’s operating system, but it requires root/sudo access. This required me to ensure my root user could ssh to my server using an authorized key (ie: no password).
As root I created my RSA SSH key:
ssh-keygen -t rsa
And appended the contents of /root/.ssh/id_rsa.pub to my server in file: /home/MYUSER/.ssh/authorized_keys
Here is the script I created to do the IP scan, dump the results to a file, scan for the IP, and push it to my server.
#!/usr/bin/env ruby
# define paths
nmap_dir = '/var/root/scripts'
output_file = "#{nmap_dir}/nmap_results.txt"
ip_file = "#{nmap_dir}/ip.txt"
# execute nmap. "-oG" outputs to a file in a grep-able format
`nmap -p 80 10.0.1.* --open -oG #{output_file} -O`
# read in file
contents = File.read output_file
# define regex to find IP, based on IP camera type (ex: foscam)
ip_regex = /^Host:\s+([0-9\.]+)\s+.*foscam/i
regex_results = contents.scan ip_regex
ip = nil
begin
ip = regex_results[0][0]
rescue
end
if !ip.nil? && !ip.empty?
# write ip to file with timestamp
File.open(ip_file, 'w') {|f| f.write "#{ip}\t#{Time.now}" }
# rsync to server
`rsync -avz #{ip_file} MYUSER@MYHOST.com:/my/public/web/path/ip.txt`
end
I then cron’d it to run every 5 minutes. edit file: /etc/crontab, added:
*/5 * * * * root /var/root/scripts/nmap_ip_scan.rb 2>/dev/null