Using Python Fabric without the command-line tool (fab)

后端 未结 5 988
旧时难觅i
旧时难觅i 2021-02-01 06:19

Altough Fabric documentations refers to a way of using the library for SSH access without requiring the fab command-line tool and/or tasks, I can\'t seem to manage a way to do i

5条回答
  •  时光说笑
    2021-02-01 06:58

    Here are three different approaches all using the execute method

    from fabric.api import env,run,execute,hosts
    
    # 1 - Set the (global) host_string
    env.host_string = "hamiltont@10.0.0.2"
    def foo():
      run("ps")
    execute(foo)
    
    # 2 - Set host string using execute's host param
    execute(foo, hosts=['hamiltont@10.0.0.2'])
    
    # 3 - Annotate the function and call it using execute
    @hosts('hamiltont@10.0.0.2')
    def bar():
      run("ps -ef")
    execute(bar)
    

    For using keyfiles, you'll need to set either env.key or env.key_filename, as so:

    env.key_filename = 'path/to/my/id_rsa'
    # Now calls with execute will use this keyfile
    execute(foo, hosts=['hamiltont@10.0.0.2'])
    

    You can also supply multiple keyfiles and whichever one logs you into that host will be used

提交回复
热议问题