python构造模块用法

时间:2019-10-03 09:27:10

标签: python ssh fabric

尝试将结构模块用于python脚本,该脚本与远程计算机对话以运行各种命令。我打算使用Fabric作为模块来通过ssh建立和运行命令。将Fabric用作常规python模块from fabric import Connection并像python script.py

一样直接运行脚本是一种好习惯吗?

我已经对此进行了测试,并且效果很好。

谢谢

1 个答案:

答案 0 :(得分:1)

Fabric2是需要与python 2.7+一起使用的。通过从命令行运行def main(): from pathlib import Path from contextlib import ExitStack from csv import reader from collections import defaultdict master_dict = defaultdict(list) glob_pattern = "[!output]*.csv" with ExitStack() as stack: readers = [reader(stack.enter_context(path.open("r"))) for path in Path(".").glob(glob_pattern)] for reader in readers: for row in reader: key, value = row master_dict[key].append(value) with Path("output.csv").open("w") as master_file: for key, value_list in master_dict.items(): master_file.write(",".join([key] + value_list) + "\n") return 0 if __name__ == "__main__": import sys sys.exit(main()) 来安装它!

然后使用以下代码创建一个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

更新

您可以将deploy()函数放在fab 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() 从命令行执行文件!