Python Fabric 模块使用

Python Fabric module usage

正在尝试将 Fabric 模块用于 Python 脚本,该脚本与远程机器对话以执行 运行 各种命令。我计划使用 Fabric 作为模块来建立 运行 ssh 上的命令。将 Fabric 作为常规 Python 模块 from fabric import Connection 和 运行 脚本直接使用 python script.py

是好习惯吗

我已经测试过了,它工作正常。

Fabric2 是您需要与 python 2.7+ 一起使用的。从命令行通过 运行 pip install fabric2 安装它!

然后创建一个fabfile.py并使用以下代码:

@task
def deploy(ctx, env=None):
    try:
        with connection(host=REMOTE_HOST, user=REMOTE_HOST_USERNAME,) as c:
            c.run('whoami')
            c.run('echo "do what you want to do"')
            c.run('mkdir new_dir')
    except AuthenticationException as message:
        print(message)
    except SSHException as message:
        print(message)

转到您 fabfile.py 所在的目录并从命令行执行此命令:

fab deploy 

更新

你可以把 deploy() 函数放在里面 main.py

from fabric import Connection as connection, task
from paramiko import AuthenticationException, SSHException


def deploy():
    try:
        with connection(host='faceai-uat', user='admin.peshmerge') as c:
            c.run('whoami')
            c.run('echo "do what you want to do"')
            c.run('mkdir new_dir')
    except AuthenticationException as message:
        print(message)
    except SSHException as message:
        print(message)

def main():
    print("Start deploying")
    deploy()


if __name__ == "__main__":
    main()

通过命令行python3 main.py执行文件!