Search code examples
sqlitestdoutosquery

How to save output of SQL query fired from Osquery to a file


I have installed Osquery utility on my machine. When I fire an SQL command, it gives output to STDOUT. Is there any way to redirect that output to a file?

$ sudo osqueryi 
I0314 10:57:51.644351  3958 database.cpp:563] Checking database version for migration
I0314 10:57:51.644912  3958 database.cpp:587] Performing migration: 0 -> 1
I0314 10:57:51.645279  3958 database.cpp:619] Migration 0 -> 1 successfully completed!
I0314 10:57:51.645627  3958 database.cpp:587] Performing migration: 1 -> 2
I0314 10:57:51.646088  3958 database.cpp:619] Migration 1 -> 2 successfully completed!
Using a virtual database. Need help, type '.help'
osquery> 
osquery> 
osquery> SELECT * from memory_info;
+--------------+-------------+----------+----------+-------------+-----------+----------+------------+-----------+
| memory_total | memory_free | buffers  | cached   | swap_cached | active    | inactive | swap_total | swap_free |
+--------------+-------------+----------+----------+-------------+-----------+----------+------------+-----------+
| 513617920    | 270921728   | 15110144 | 99860480 | 0           | 145080320 | 59494400 | 0          | 0         |
+--------------+-------------+----------+----------+-------------+-----------+----------+------------+-----------+
osquery> 

I want this output in a file. I checked Osquery official documentation. But it hasn't been helpful to solve this particular problem. https://osquery.readthedocs.io/en/stable/introduction/sql/#sql-as-understood-by-osquery


Solution

  • You can use the redirection facilities of your shell:

    $ osqueryi --json 'select * from osquery_info' > res.json
    $ cat res.json
    [
      {"build_distro":"10.12","build_platform":"darwin","config_hash":"e7c68185a7252c23585d53d04ecefb77b3ebf99c","config_valid":"1","extensions":"inactive","instance_id":"38201952-9a75-41dc-b2f8-188c2119cda1","pid":"26255","start_time":"1552676034","uuid":"4740D59F-699E-5B29-960B-979AAF9BBEEB","version":"3.3.0","watcher":"-1"}
    ]
    

    Note that in this example we use JSON output. There are other options available: --csv, --line, --list.

    As seph explained in https://stackoverflow.com/a/55164199/491710, it is a common use-case to schedule queries in osqueryd and push the results into a logging pipeline.