Skip to content

Instantly share code, notes, and snippets.

@brodo
Last active October 21, 2021 18:32
Show Gist options
  • Save brodo/5039733 to your computer and use it in GitHub Desktop.
Save brodo/5039733 to your computer and use it in GitHub Desktop.
Serialsniffer for Mac OS X: Sniffs an OPEN serial connection. The connection must be open before you run the script.
#!/usr/bin/env ruby
# Sniffs a serial Connection. Prints all unprintable characters!
# Only tested under Mac OS X 10.8. (should work with earlier versions)
# Uses dtruss, which comes with Mac OS.
#
# Usage:
# $ ./serialsniffer.rb <serial device>
#
# Example:
# $ ./serialsniffer.rb /dev/tty.usbserial-A6008j9P
require 'pty'
raise 'Must run as root' unless Process.uid == 0
raise 'Please specify a device to sniff. E.g. /dev/tty.usb1' unless ARGV.length == 1
raise 'Device does not exist!' if `ls #{ARGV[0]} 2>&1`.include? 'No such file or directory'
tty_name = ARGV[0].split('/')[-1]
currently_sniffing = false
def run_dtruss(pid, file_desc_hex)
cmd = "dtruss -p #{pid}"
PTY.spawn cmd do |r,w, pid|
begin
currently_sniffing = true
r.sync
r.each_line do |l|
if l.start_with? "read(#{file_desc_hex}" or l.start_with? "write(#{file_desc_hex}"
puts l.split('"')[1]
end
if l[0..4] == 'kill('
currently_sniffing = false
Process.kill(9, pid)
end
end
rescue Errno::EIO => e
# simply ignoring this
rescue Errno::ECHILD => e
# simply ignoring this
ensure
::Process.wait pid
end
end
end
while true
if not currently_sniffing
processes = `ps -a`
pid_line = processes.split("\n").select {|line| line.split[1]==tty_name }
if pid_line.length > 0
pid = pid_line[0].split[0]
#Find out which file descriptor the TTY has
openFiles = `lsof -p #{pid}`
tty_line = openFiles.split("\n").select {|line| line.include? " #{ARGV[0]}"}
file_descriptor = tty_line[0].split[3].scan(/\d+/)[0]
file_descriptor_hex = "0x#{file_descriptor.to_i.to_s(16)}"
run_dtruss(pid, file_descriptor_hex)
end
sleep 1
end
end
@melyux
Copy link

melyux commented Oct 21, 2021

Is it... supposed to output anything? It just sits there.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment