How to answer to prompts automatically with python fabric?

后端 未结 6 1244
一个人的身影
一个人的身影 2020-11-29 23:42

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

6条回答
  •  醉梦人生
    2020-11-30 00:40

    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:

    1. 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 expect
    2. The pattern 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.
    3. 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.

提交回复
热议问题