miniexpect: A small expect library for C

The rewrite of virt-p2v dumps the old system where the front end and the back end talked over a custom protocol. In the new version, virt-p2v ssh’es into the conversion server and runs commands directly.

However to do this I needed to be able to control the interactive ssh process from the program.

The classical way to do this is using Tcl’s expect tool. You can write expect scripts like this:

#!/usr/bin/expect  --
set timeout 30
spawn ssh user@remote
expect {           
    password: {
        send "secret\r"
    "yes/no)?" {
        send "yes\r"
        set timeout -1
    timeout {
    eof {

This doesn’t work so well from C, but luckily there is libexpect. Unfortunately the libexpect API isn’t thread-safe (we ❤ globals!), doesn’t adhere to modern C standards, and the library is quite buggy.

How hard would it be to write an expect replacement? At first glance it seems like it would be hard. libexpect has to contain a complete regular expression implementation (and a glob implementation too), because it has to be able to drive the regular expression parser over the incomplete data that it is reading from the subprocess.

However here is an observation: PCRE provides an implementation of partial pattern matching meaning that you can match on the incomplete data you’ve already received from the subprocess and decide whether you have a complete match or a partial match (in the partial match case you just wait for more data to arrive).

Using PCRE partial matches, I was able to write a pretty good mini-library for expect in just under 500 lines of code. The library is here:;a=tree

Leave a comment

Filed under Uncategorized

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.