Export cookies from Safari in Sierra

Published

I wanted to automate a batch processing job and was too lazy to programmatically fetch the cookies by emulating a login form so I looked for a way to just reuse my cookies.

That should be pretty easy in general, for example with the Python bindings on macOS, but the syntax changed a bit between 10.10 and 10.12 respectively, so I fired up Xcode and the following ten-ish lines of Swift work nicely in generating output which is fit for wget and other tools using the ancient cookie file format.

import Foundation

print("The url to fetch:", terminator: " ")
let response = readLine(strippingNewline: true)

let storage = HTTPCookieStorage.sharedCookieStorage(forGroupContainerIdentifier: "Cookies")
let cookies = storage.cookies(for: URL(string: response!)!)

print("# HTTP Cookie File\n")

for cookie in cookies! {
    var secure = "FALSE"
    if (cookie.isSecure) {
        secure = "TRUE"
    }
    var expires:Int = Int(cookie.expiresDate!.timeIntervalSince1970)
    print("\(cookie.domain)\tTRUE\t\(cookie.path)\t\(secure)\t\(expires)\t\(cookie.name)\t\(cookie.value)")
}

I don’t get points for exception handling or elegance but I have my 🍪.

I haven’t yet figured out a good workflow of generating such CLI binaries without hunting for them in the build folder and copying them over, input on that is very welcome.