Skip to main content

Run a Command Script

Run by Command Script runs your own scripts on macOS, Windows, and Linux devices, from the Swif console. Use it for system settings, app management, or any task you'd otherwise do by hand on each device. Commands can run when you choose, on a schedule, or when another system calls a webhook.

For other kinds of commands, see Run Commands by Script, OSQuery, File, or Git Repo.


Who a command runs as

Run as

macOS

Windows

Linux

Runs as

System (default)

✅

✅

✅

root on macOS and Linux, SYSTEM on Windows

Local User

✅

✅

✅

The user signed in to the device

Swif Admin Account

✅

—

✅

Swif's administrator account on the device

System commands already run with full administrator rights, so you don't need sudo in them.


Create a command

  1. In Swif, go to Device Management > Commands, and click Create New Command.

  2. Fill in:

    • Command Name: A clear name, such as Install Updates

    • Description: Optional. What the command does.

    • OS Type: macOS, Windows, or Linux

    • Command Script: Your script. For macOS and Linux, a bash or sh script, such as one starting with #!/bin/bash. For Windows, PowerShell or Batch.

    • Run As: System, the default, or Local User. See Run as the signed-in user below.

  3. Under Run Schedule, choose:

  4. Set Command Status:

    • Enabled: the command is active as soon as you create it, and runs at its scheduled times.

    • Disabled: it doesn't run on its schedule until you enable it.

  5. Optional:

    • Timeout After: stop the command if it runs longer than this many seconds.

    • Run on Swif Admin Account: on macOS and Linux, run as Swif's administrator account. See Run on the Swif admin account below.

  6. Click Continue, and choose the devices or device groups.

Check that it's active. On the command's page, the status shows Active, and Running on shows how many devices and device groups it's assigned to.


Run a command now

Click Run. Online devices get the command right away, without waiting for their next check-in. Offline devices run it when they next connect.


Run as the signed-in user

Set Run As to Local User, to run the command as the user signed in to the device. Use it for anything that depends on the user:

  • their files and settings, such as %USERPROFILE% on Windows, or ~ on macOS and Linux

  • apps installed only for them, such as Cursor or VS Code extensions

  • anything that shows on their screen

If no one is signed in when the command runs, it doesn't run.

To change a user's files from a System command, for example, when no one may be signed in, run that part as the user. On macOS:

loggedInUser=$(stat -f%Su /dev/console)
sudo -H -u "$loggedInUser" <command>

The -H sets the home folder to the user's own. Without it, the command uses root's home folder, /var/root, and often fails with permission denied.


Run on the Swif admin account

On macOS and Linux, turn on Run on Swif Admin Account to run as Swif's administrator account, instead of root. Check that the Swif admin account isn't turned off.

Use the Swif admin account's name and password

For commands that need the Swif admin account's credentials, such as granting a Secure Token on macOS, use these placeholders. Swif fills them in when the command runs, so you never put the password in the script:

Placeholder

Replaced with

{{SWIF_ADMIN_USER}}

The Swif admin account's username

{{SWIF_ADMIN_PASSWORD}}

The Swif admin account's password, on that device

For example, to turn on a Secure Token for a user, on macOS:

sysadminctl -adminUser {{SWIF_ADMIN_USER}} -adminPassword '{{SWIF_ADMIN_PASSWORD}}' -secureTokenOn YOUR_USER -password 'YOUR_USER_PASSWORD'

To turn it off:

sysadminctl -adminUser {{SWIF_ADMIN_USER}} -adminPassword '{{SWIF_ADMIN_PASSWORD}}' -secureTokenOff YOUR_USER -password 'YOUR_USER_PASSWORD'

On Windows, commands like runas ask for the password interactively, and don't accept it in a script. Commands run as System by default, which usually avoids the need. For other options, such as PowerShell's Start-Process -Credential, see How to run Commands as Administrator on Windows.

For other placeholders, see Using Placeholders in Command Scripts.


Example: Use Cloudflare DNS over HTTPS on Windows

This command sets managed Windows devices to use Cloudflare's 1.1.1.1 resolver, with DNS over HTTPS (DoH). DoH encrypts DNS lookups between the device and Cloudflare, so they can't be read on the network.

Setting

Value

Primary DNS

1.1.1.1

Secondary DNS

1.0.0.1

DoH template

https://cloudflare-dns.com/dns-query

For other resolver options, see Cloudflare's 1.1.1.1 documentation.

Before you begin

  • Test it on a small device group first.

  • It changes DNS on every active physical network adapter. Devices that rely on internal DNS, for Active Directory, internal apps, or private hostnames, may lose access to them.

  • VPN, security, or network software may override these settings.

  • It turns off fallback to unencrypted DNS, so lookups fail if Cloudflare's DoH isn't reachable.

Create the command

Field

Value

Command Name

Configure Cloudflare DNS over HTTPS

OS Type

Windows

Run As

System

Run Schedule

Run Manually while testing. Later, a schedule, to keep it applied.

Use this PowerShell script:

$ErrorActionPreference = "Stop"

$DohTemplate = "https://cloudflare-dns.com/dns-query"
$DnsServers = @(
"1.1.1.1",
"1.0.0.1"
)

# Register or update the Cloudflare DoH resolvers.
foreach ($Server in $DnsServers) {
$ExistingServer = Get-DnsClientDohServerAddress `
-ServerAddress $Server `
-ErrorAction SilentlyContinue

if ($ExistingServer) {
Set-DnsClientDohServerAddress `
-ServerAddress $Server `
-DohTemplate $DohTemplate `
-AllowFallbackToUdp $false `
-AutoUpgrade $true
}
else {
Add-DnsClientDohServerAddress `
-ServerAddress $Server `
-DohTemplate $DohTemplate `
-AllowFallbackToUdp $false `
-AutoUpgrade $true
}
}

# Find active physical network adapters.
$Adapters = Get-NetAdapter -Physical |
Where-Object { $_.Status -eq "Up" }

if (-not $Adapters) {
throw "No active physical network adapters were found."
}

# Assign Cloudflare DNS to each active physical adapter.
foreach ($Adapter in $Adapters) {
Set-DnsClientServerAddress `
-InterfaceIndex $Adapter.ifIndex `
-ServerAddresses $DnsServers

Write-Output "Configured Cloudflare DoH on adapter: $($Adapter.Name)"
}

Clear-DnsClientCache

Write-Output "Cloudflare DNS over HTTPS configuration completed."

Get-DnsClientDohServerAddress |
Where-Object { $_.ServerAddress -in $DnsServers } |
Format-Table ServerAddress, DohTemplate, AllowFallbackToUdp, AutoUpgrade

It's safe to run more than once. It updates an existing Cloudflare DoH setting, instead of adding a duplicate.

Check that it worked

In the command's report, check that both Cloudflare addresses appear, with:

  • AutoUpgrade set to True

  • AllowFallbackToUdp set to False

  • the DoH template set to https://cloudflare-dns.com/dns-query

Or, on the device:

Get-DnsClientDohServerAddress |
Where-Object {
$_.ServerAddress -in @("1.1.1.1", "1.0.0.1")
}

Get-DnsClientServerAddress -AddressFamily IPv4

Resolve-DnsName example.com

For more on encrypted DNS in Windows, see Microsoft's netsh dnsclient documentation.

Undo it

To return active physical adapters to the DNS servers from DHCP, run this as System:

$Adapters = Get-NetAdapter -Physical |
Where-Object { $_.Status -eq "Up" }

foreach ($Adapter in $Adapters) {
Set-DnsClientServerAddress `
-InterfaceIndex $Adapter.ifIndex `
-ResetServerAddresses

Write-Output "Restored automatic DNS settings on adapter: $($Adapter.Name)"
}

Clear-DnsClientCache

Write-Output "DNS settings have been restored to their network defaults."

The Cloudflare DoH setting may stay in Windows, but isn't used unless an adapter is set to Cloudflare's addresses again.


View a command's results

  1. Go to Device Management > Commands.

  2. Open the command, and click View Command Report, to see each device's result, output, and errors.


Trigger a command with a webhook

Other systems can run a command through a webhook, such as a CI/CD pipeline, a security scanner, or a monitoring tool. Available on the Growth plan and above, for your own commands and system command templates.

What can be triggered:

  • Your own commands, whether they run manually, or on a schedule. A scheduled command still runs on its schedule too.

  • System command templates, such as Reboot, Shutdown, Remote Lock (Lost Mode), and Wipe (factory reset)

Set it up

  1. Create or open the command.

  2. In Webhook Configuration, set up the webhook.

  3. In the command's Command Details panel, create a command token. You can restrict it to an IP address or range, so only your trusted systems can use it.

  4. Copy the Webhook URL, and the token, into your other system.

The Webhook section of Command Details shows the command's URL, and its tokens. A token shows Expires in Xm while it's valid, and Expired after that. Create a token for each system that calls the webhook, so you can revoke one without affecting the others. Deleting a token stops its access right away.

Call the webhook

Send a POST request to the command's Webhook URL, from Command Details. Put the command token in the Authorization header, as Bearer followed by the token, the same way as Swif's Public APIs.

Without a body, the command runs on all the devices and device groups it's assigned to:

curl --request POST '<Webhook URL>' \
--header 'Authorization: Bearer <command token>'

To run it on specific devices only, list their device IDs:

curl --request POST '<Webhook URL>' \
--header 'Authorization: Bearer <command token>' \
--header 'Content-Type: application/json' \
--data '{
"deviceIDs": [
"device_id_1",
"device_id_2"
]
}'

Replace <Webhook URL> and <command token> with the values from Command Details.

Use device IDs, not serial numbers, since serial numbers aren't always reliable on Windows and Linux. Find a device's ID in the API, under mdmDeviceInfo > mdmDeviceId. See Public APIs: Device and Evidence Retrieval.

Safeguards for destructive commands

  • Two-factor verification: if your organization uses 2FA, it's required before a destructive command, such as Wipe, is queued.

  • Warnings: Swif shows a risk warning for high-risk webhook commands.

  • Wipe type: for Wipe, you must choose the type, such as partial or full.

  • Remote Lock on macOS needs a 6-digit PIN, as Apple requires.

Common uses

  • Remediation: a security scanner finds a problem on a device, and triggers a fix script, or a Remote Lock, for that device.

  • Recovery: a monitoring tool sees a service fail, and triggers a Reboot.

  • Deployments: a CI/CD pipeline runs a script to clear caches, or update settings, after a release.


Troubleshooting


Related resources

Did this answer your question?