完整的代碼已經在github開源:github.com/CTC-maxiao/…python
前面的幾節咱們已經完成了執行字典生成器和執行字典執行器,如今咱們只須要編寫一個入口程序來接收外界輸入而後自動生成執行字典列表,而後再經過task執行器來依次執行任務,就能夠徹底整個程序的編寫。git
import sys
import getopt
from task_executor import TaskExecutor
from get_tasklist import getTaskList
#getopt是一個很是好用的python庫,設定的參數後加":"意味這個參數須要輸入
opts,args = getopt.getopt(sys.argv[1:],'-u:-p:-y:-h-v',['user=','password=','yamlfile=','help','version'])
for opt_name,opt_value in opts:
if opt_name in ('-u','--user'):
ssh_user = opt_value
if opt_name in ('-p','--password'):
ssh_pwd = opt_value
if opt_name in ('-y','--yamlfile'):
yaml_file = opt_value
if opt_name in ('-h','--help'):
print "help you"
sys.exit()
if opt_name in ('-v','--version'):
print "version 1.0"
sys.exit()
task_list = getTaskList.get_final_task_list(ssh_user,ssh_pwd,yaml_file)
for task in task_list:
tmp=TaskExecutor.run_task(task)
print tmp
複製代碼
這裏咱們使用getopt庫,這個庫能夠簡潔的接收傳入參數,而且支持長參數和短參數兩種形式。github
程序至此就已經算是寫好了,雖然還很不完善,但已經實現了基本的功能。咱們編寫一個簡單的playbook來測試一下最終的程序。shell
---
- name: test program on remote machine
host: 192.168.1.34
tasks:
- task_name: create test folder on remote machine
become: yes
become_user: root
action_type: shell
action: mkdir /opt/mstr/test
- task_name: create test folder on localhost
action_type: shell
action: mkdir /opt/mstr/test
delegate_to: localhost
複製代碼
這個playbook很是簡單,執行後會在本機和遠程機器上生成一個文件夾。bash
如今咱們來執行這個playbook:ssh
python main.py -u test_user -p test_pwd -y /opt/mstr/test.yaml
複製代碼
運行結束後能夠看到,本機和遠程機器上成功生成了相應的文件夾。測試
咱們的playbook的格式基本與ansible的一致,但也有一些不一樣點須要注意:ui
若是你須要爲這個程序編寫playbook,請注意以上幾點。另外,完整的程序我已經開源到github,歡迎試用和幫忙找bug。 github地址: github.com/CTC-maxiao/…spa