I want to run a command which prompts me to enter yes/no or y/n or whatever. If I just run the command local(\"my_command\")
then it stops and asks me for input
In Fabric 2.1, this can be accomplished using the auto-respond example that is available through the invoke package (a dependency of Fabric 2.1):
>>> from invoke import Responder
>>> from fabric import Connection
>>> c = Connection('host')
>>> sudopass = Responder(
... pattern=r'\[sudo\] password:',
... response='mypassword\n',
... )
>>> c.run('sudo whoami', pty=True, watchers=[sudopass])
[sudo] password:
root
Note that this is not limited to sudo passwords and can be used anywhere where you have a pattern to match for and a canned response (that may not be a password).
There are a couple of tips:
pty=True
is NOT necessary but could be important because it makes the flow seem more realistic. e.g. if you had a prompt expecting a yes/no answer to proceed, without it(pty=True
) your command would still run; except, your choice/input(specified by response
) won't be shown as typed as the answer as one might expectpattern
specified within the Responder
can often include spaces at the end of the line so try adding spaces when the watcher
doesn't seem to match.According to the note discussed at the end of the watcher docs:
The pattern argument to Responder is treated as a regular expression, requiring more care (note how we had to escape our square-brackets in the above example) but providing more power as well.
So, don't forget to escape (using backslashes) where necessary.