Benjamin Sago / ogham / cairnrefinery / etc…

Technical notes List open ports with SwiftBar

Occasionally, I’ll accidentally leave a server running, or a parent process will crash and disown one of its children, and I’ll try to run something only to be met with “port already in use”.

So to keep an eye on which ports are being used, I wrote a SwiftBar script. SwiftBar is a macOS application that provides an easy way to put text and dropdown menus in the Menu Bar without having to learn the intricacies of Mac development.

A screenshot of my ports SwiftBar script, with three open ports detected.

The script is written in Ruby, because that’s the language I already know:

#!/usr/bin/env ruby
require 'socket'

  8500 => 'consul',
  4646 => 'nomad',
  8000 => 'project-one',
  8080 => 'project-two',

opens, closeds = PORTS.partition do |port, str|
  Socket.tcp('localhost', port, connect_timeout: 1) { true } rescue false

if ENV['OS_APPEARANCE'] == 'Dark'
  menu_colour = '#aaaaaa'
  entry_colour = '#dddddd'
  menu_colour = '#777777'
  entry_colour = '#333333'

puts "Ports: %d | size=10 color=%s" % [opens.length, menu_colour]
puts "---"

opens.each do |port, str|
  puts "%s: %s | size=11 color=%s" % [port, str, entry_colour]

Now, whenever a port seems suspiciously in use, all I have to do is move my eyes to the menu bar and see what’s running.