Multi-Factor Authentication in Shell Scripting

The login prompt flashes on the screen. You type your password. It’s not enough.

Multi-Factor Authentication (MFA) in shell scripting is the next barrier. One factor can be stolen. Two or more make unauthorized access far harder. Implementing MFA in your scripts is simple if you know where to start, and vital if you care about security.

MFA combines something you know (password), something you have (token, device), and sometimes something you are (biometrics). In shell scripting, the most common approach is pairing passwords with time-based one-time passwords (TOTP) or an API-driven secondary check. The goal is to integrate these steps into automation without breaking workflows.

Start by securing password entry with read -s to keep it hidden in terminal history. For the second factor, use tools like oathtool for TOTP generation, or hit verification endpoints from providers such as Google Authenticator, Authy, or Okta via curl. Scripts can call these tools, compare the entered code against the server’s expected value, then decide to continue or exit.

Example MFA flow in shell scripting:

  1. Prompt for the user’s password.
  2. Validate against a local hash or API.
  3. Prompt for the TOTP code.
  4. Validate using oathtool or provider API.
  5. Continue execution only if both checks pass.

Always store secrets outside of the script itself. Use environment variables, encrypted files, or secure vault services. Log failures but keep logs sanitized to prevent leaking sensitive data. Combine MFA with role-based permissions so that even a compromised account has limited reach.

Testing the MFA shell script is as important as writing it. Simulate invalid codes, expired codes, and repeated failures. Measure latency between factors. Ensure your automation handles downtime in the authentication service gracefully.

Done right, MFA in shell scripts raises your system’s defense without crushing usability. It’s low-cost, fast to build, and high-impact.

Want to see MFA shell scripting in action with working code you can deploy instantly? Go to hoop.dev and watch it go live in minutes.