# Secrets in Expect scripts: keys first, then echo, logs and host keys

> Expect's own manual says that storing a password in a script is not recommended, because anything stored on a computer can be read. The safer orders are, in turn: no password at all (an SSH key held by an agent), a password typed at run time with echo off, a password read from the environment or from a file only its owner can read. Each one has a leak beside it that is easy to miss: a log file records what expect_user reads even with echo off, the diagnostics print every send in full, the environment is inherited by every program the script spawns, and Tcl 9 reads 0600 as a decimal number. Here is each route with its leak, checked against the real Expect 5.45.4, and why StrictHostKeyChecking=accept-new beats no.

Source: https://ronutz.com/en/learn/expect-secrets-and-safe-scripts  
Updated: 2026-10-27  
Related tools: https://ronutz.com/en/tools/expect-script-explainer, https://ronutz.com/en/tools/expect-script-builder

---

The [Expect](https://ronutz.com/en/glossary/expect) manual is blunt about passwords in scripts. "It is often useful to store passwords (or other private information) in Expect scripts. This is not recommended since anything that is stored on a computer is susceptible to being accessed by anyone. Thus, interactively prompting for passwords from a script is a smarter idea than embedding them literally." Most real scripts end up somewhere between those sentences: they run from a scheduler, nobody is there to type, and the device at the other end wants to be logged in to. This article walks the safer routes in order of preference and, for each, the place where a secret leaks anyway. Every behaviour was run against the real Expect 5.45.4 on [Tcl](https://ronutz.com/en/glossary/tcl) 8.6.14, with fake devices in a container; the documents quoted were read on 2026-10-27.

## First choice: no password, a key and an agent

When the far end is an SSH server, the best password in a script is none. OpenSSH's client reads an identity from the file named by `IdentityFile` in ssh_config(5), and `ssh-agent` "is a program to hold private keys used for public key authentication": the key is unlocked once, with its passphrase, by `ssh-add` (which "adds private key identities to the authentication agent"), and every connection after that authenticates without a password prompt for the script to answer. `IdentitiesOnly yes` restricts ssh to the identities configured "even if ssh-agent(1) ... offers more identities"; the page says the option "is intended for situations where ssh-agent offers many different identities".

The key file has a permission rule that ssh enforces itself: private key files "contain sensitive data and should be readable by the user but not accessible by others (read/write/execute). ssh will simply ignore a private key file if it is accessible by others." A passphrase, set when the key is generated, encrypts "the sensitive part of this file".

The other option for scripts is `BatchMode`: "If set to yes, user interaction such as password prompts and host key confirmation requests will be disabled. This option is useful in scripts and other batch jobs where no user is present to interact with ssh(1)." With `-o BatchMode=yes`, ssh never stops to ask for a password nobody will type: when the key no longer works, the connection fails, the program ends, and the script sees an end of file, which an `eof` arm can report with its own exit code (the [timeouts and eof](https://ronutz.com/en/learn/expect-timeouts-eof-and-loops) article covers those arms).

## Second choice: asked at run time, with echo off

When a person starts the script, the manual's own idiom keeps the password out of every file:

```tcl
stty -echo
send_user "Password: "
expect_user -re "(.*)\n"
set password $expect_out(1,string)
stty echo
send_user "\n"
```

The manual introduces it as a way "to temporarily disable echoing. This could be used in otherwise-automatic scripts to avoid embedding passwords in them." Note the `stty echo` straight after the read: a script that leaves echo off returns a terminal that no longer shows what is typed, and the [Expect script explainer](https://ronutz.com/en/tools/expect-script-explainer) flags an `stty -echo` that is never undone (its check E15).

In the run, an outer Expect played the person at a terminal. With `stty -echo` the typed password never appeared on the screen; without it, it did. But the same script also had a `log_file` open, and there the password was in both cases: `log_file` "will record a transcript of the session", and what `expect_user` reads from the person is part of the session. Echo controls the screen, not the log. Stop the log around the read and start it again after (`log_file` with no argument "will stop recording", and by default it "appends to old files rather than truncating them"); in the run, that kept the password out of the file:

```tcl
log_file
expect_user -re "(.*)\n"
log_file -a $logpath
```

## Third choice: the environment, or a file only its owner can read

An unattended script needs the secret from somewhere. Two places keep it out of the script's text.

**The environment.** Tcl keeps the environment in the array `env`: "Reading an element will return the value of the corresponding environment variable", and "Changes to the env array will affect the environment passed to children by commands like exec". Expect's `spawn` passes it on as well: in the run, a shell spawned after the variable was set printed it. So read the value into an ordinary variable and remove it before spawning anything ("Unsetting an element of env will remove the corresponding environment variable"); after `unset env(DEVPASS)` the next spawned shell saw nothing.

```tcl
set password $env(DEVPASS)
unset env(DEVPASS)
spawn ssh -o StrictHostKeyChecking=accept-new admin@$host
```

**A file.** A file holding one line, readable only by the account that runs the script, follows the same rule ssh applies to its keys. Tcl can create it with tight permissions (when `open` creates a file, "permissions (an integer) is used to set the permissions for the new file in conjunction with the process's file mode creation mask") and check them before every read with `file attributes`, whose `-permissions` option "retrieves or sets a file's access permissions, using octal notation by default". Tcl 9 changed one detail that matters here: "0NNN format is no longer octal interpretation. Use 0oNNN". So `0600` in Tcl 9 is the decimal six hundred, and the octal string that `file attributes` returns, such as `00600`, has to be read with `scan ... %o`, which takes "an octal integer", instead of being used as a number. Written that way, the check works the same in Tcl 8.6 and Tcl 9:

```tcl
proc read_secret {path} {
    scan [file attributes $path -permissions] %o mode
    if {$mode & 0o077} {
        error "refusing $path: group or others may read it"
    }
    set ch [open $path r]
    set secret [gets $ch]
    close $ch
    return $secret
}
```

In the run, a file created with `open $f {WRONLY CREAT TRUNC} 0o600` reported `00600` and was read; after a change to 0644 the procedure refused it. The site's article on [file modes](https://ronutz.com/en/learn/file-modes-octal-symbolic-and-the-special-bits) explains the octal digits.

Whichever source the password comes from, send it with `send --`: the flag "forces the next argument to be interpreted as a string rather than a flag", the "reliable mechanism to specify variable strings without being tripped up by those that accidentally look like flags", and a password may well start with a dash.

The route the explainer exists to catch is the last one: a literal password in a `send` after a password prompt, or in a variable named like one. Its check E1 rates that as an error, and it masks the value in its own output.

## What reaches the screen, the log and the diagnostics

Three outputs can carry a secret, and they follow different rules.

**The screen.** "By default, the send/expect dialogue is logged to stdout (and a logfile if open). The logging to stdout is disabled by the command "log_user 0" and reenabled by "log_user 1"." What appears is what the program sends back, so a password reaches the screen only if the program echoes it. In the run, a device that turned echo off for its password prompt, as ssh and login programs do, left nothing to see; a careless device that echoed it put the password on the screen.

**The log file.** It holds the same dialogue as the screen, plus `send_user` text and what `expect_user` reads, as above. One flag decides what happens under `log_user 0`: "The -a flag forces output to be logged that was suppressed by the log_user command." In the run, a log opened without `-a` received none of the dialogue while `log_user` was 0, and one opened with `-a` received all of it, including the echoed password from the careless device. A quiet script with a full record therefore uses `log_user 0` with `log_file -a`, and stops the log around any exchange that might echo a secret. The explainer notes a `log_user 0` that is never turned back on (E12), so an operator is not left with no output at all.

**The diagnostics.** `exp_internal 1` and `expect -d` print "every character received, and every attempt made to match the current output against the patterns", and in the run they also printed every `send` in full: `send: sending "S3cr3t-Run06\r" to { exp3 }`, even with a device that never echoed it. A diagnostic file opened with `exp_internal -f` gets the same line. Turn diagnostics off around the send and back on after it; `exp_internal -info` returns the current setting so it can be restored exactly:

```tcl
set diag [exp_internal -info]
exp_internal 0
log_file
send -- "$password\r"
expect -re {[>#] $}
log_file -a $logpath
eval exp_internal $diag
```

## Host keys: accept-new, not no

The first connection to a new host is where many scripts meet an unexpected question. ssh_config(5) defines `StrictHostKeyChecking`, and its default, `ask`, means "new host keys will be added to the user known host files only after the user has confirmed that is what they really want to do". The script that expected a password prompt gets a `(yes/no)` question instead.

The common fix, `StrictHostKeyChecking=no`, answers more than that question. With `no` or `off`, "ssh will automatically add new host keys to the user known hosts files and allow connections to hosts with changed hostkeys to proceed, subject to some restrictions". A changed host key is the warning sign of a man-in-the-middle, the very attack the option's own page says `yes` gives "maximum protection against". `accept-new` takes only the safe half: "ssh will automatically add new host keys to the user's known_hosts file, but will not permit connections to hosts with changed host keys". That is the setting for an unattended script that meets new devices; `yes`, with a `known_hosts` file prepared in advance, is stricter still, since it "forces the user to manually add all new hosts".

With `accept-new`, a device whose key changed makes ssh refuse to connect, and the script sees an end of file instead of a prompt, which its `eof` arm turns into a clear failure. The explainer's check E10 notes an ssh spawned with none of `no`, `off` or `accept-new` and no arm for the `(yes/no)` question, and it counts `accept-new` as handled.

## A short checklist

- Prefer a key in an agent, with `BatchMode=yes`, to any password.
- Never write a password in the script: the explainer's E1 is there to catch it.
- Read a typed password with `stty -echo` and turn echo back on at once; stop `log_file` around `expect_user`.
- Take a password from `env()` and unset it before `spawn`, or from a file checked for 0600 with `scan %o`, written `0o600` for Tcl 9.
- Send it with `send --`; keep `exp_internal` and the log off around that send.
- Use `StrictHostKeyChecking=accept-new`, never `no`, and give every wait an `eof` arm.

The [Expect script builder](https://ronutz.com/en/tools/expect-script-builder) writes scripts that follow this list: the password comes from the environment, unset before `spawn`, or is asked for with echo off, and never from the file; ssh uses `accept-new`; the log file opens only after the login; and every wait has an `eof` arm.

## Sources

- [expect(1), the Expect manual page, release 5.45.4 (Don Libes, NIST), in the Expect repository at core.tcl-lang.org](https://core.tcl-lang.org/expect/raw?name=expect.man&ci=expect-5-45-4) (read 2026-10-27)
- [OpenSSH ssh_config(5): StrictHostKeyChecking, BatchMode, IdentityFile, IdentitiesOnly](https://man.openbsd.org/ssh_config.5) (read 2026-10-27)
- [OpenSSH ssh(1): the private key files and their permissions](https://man.openbsd.org/ssh.1) (read 2026-10-27)
- [OpenSSH ssh-agent(1)](https://man.openbsd.org/ssh-agent.1) (read 2026-10-27)
- [OpenSSH ssh-add(1)](https://man.openbsd.org/ssh-add.1) (read 2026-10-27)
- [Tcl 9.0 manual: tclvars, the env array](https://www.tcl-lang.org/man/tcl9.0/TclCmd/tclvars.html) (read 2026-10-27)
- [Tcl 9.0 manual: open, the permissions argument](https://www.tcl-lang.org/man/tcl9.0/TclCmd/open.html) (read 2026-10-27)
- [Tcl 9.0 manual: file attributes -permissions](https://www.tcl-lang.org/man/tcl9.0/TclCmd/file.html) (read 2026-10-27)
- [Tcl 9.0 manual: scan](https://www.tcl-lang.org/man/tcl9.0/TclCmd/scan.html) (read 2026-10-27)
- [Tcl/Tk 9.0 release notes: 0NNN is no longer octal, use 0oNNN](https://www.tcl-lang.org/software/tcltk/9.0.html) (read 2026-10-27)
