腳本是一段Python代碼,要求腳本里面定義好與模板名同名的函數,作為執行任務的入口函數。
代碼限制
禁用內置函數print,while。
限制range使用,最大不超過1000。
import白名單列表:
re
json
time
datetime
IPy
hashlib
base64
uuid.uuid4
difflib
ipaddress
copy
random
math
string
禁用下劃線開頭_命名的變量/函數。
內置函數說明
logger
logger是標準模塊logging.Logger的一個實例。
用戶可以參考下?的?式輸出日志,所有的日志都會記錄在數據庫中,可以在任務管理??查詢。
def logger_example():
logger.error("an error message")
logger.warn("a warning message")
logger.info("an info message")
logger.debug("a debug message")
login_device/device_login
login_device/device_login負責處理設備的登錄登出,以及保證設備操作的串?化。
exec_cli
exec_cli負責向設備下發命令,只能用于login_device裝飾的函數中。
完整參數列表:
command: string|list,向設備下發的指令或指令列表。
timeout: int,默認65s,系統等待設備響應命令完成的超時時間,設備沒能在指定時間內完成響應則會有Timeout異常拋出。
style: string,控制返回內容結構。
simple: 回顯去除掉input command和終端提示符后剩余內容。
tuple: 將回顯內容進?拆分,返回(command,output)的列表。
verbose: 默認值,將設備回顯內容原樣返回。
strict: boolean,默認值True,是否對回顯內容作異常關鍵字判斷。如果命中關鍵字,則會拋出異常SYSTEM_BUSY或BAD_DEVICE_RESPONSE,?前關鍵字列表包括:
System is busy
Permission denied
syntax error.
Unrecognized command
Invalid command
Invalid parameter
at '^' marker
Unknown command
at '^' position.
Incomplete command
unknown command
Operation fail
error: configuration database locked by
TCAM region is not configured
Invalid input
Request denied
Authorization denied
error: commit failed
Unavailable command
Cannot apply ACL
exec_script
exec_script用于調用其他模板。
def exec_script_example(target, cli):
# 調用exec_cli_example的設備模板
return exec_script('exec_cli_example', _target=target, cli=cli)
exec_script_async
exec_script_async用于異步調用模板。
def exec_script_async_example(target, cli):
# 異步調用device_login_example的設備模板
task = exec_script('exec_cli_example', _target=target, cli=cli)
# 獲取異步任務的結果
result = task.get()
return result
current_device
current_device用于獲取當前登錄的設備。
@login_device
def get_device():
device = current_device()
device['ip'] # 設備IP
device['hostname'] # 主機名
device['domain'] # 安全域
device['space'] # 物理空間
device['status'] # 狀態
device['role'] # 角色
device['vendor'] # 廠商
device['model'] # 型號
device['sn'] # SN
device['device_id'] # id
abort
abort用于終止任務執行。
如下示例代碼,運行時,任務會執行失敗,返回為{"message": "xxx", "traceback": [[ "__shadow_{腳本MD5值}_abort_example_{版本ID}__",2,"abort_example",null]], "error_code": "OZ_USER_ABORT"}。
def abort_example():
abort("xxx")
get_exc_code
捕獲異常時,可用該函數獲取異常錯誤碼。
get_traceback
捕獲異常時,可用該函數獲取錯誤堆棧。
def exc_example():
try:
abort("xxx")
except Exception as e:
e.message #返回"xxx"
get_exc_code(e) #返回"OZ_USER_ABORT"
get_traceback() #返回[["__shadow_{腳本MD值}_{模板名}_{版本ID}__",
# {異常發生代碼行數},
# {異常所在函數名},
# null]]
輸入參數說明
設備模板默認第一個參數是_target,類型是string,可以是設備的id,設備的主機名或者IP。
輸出參數說明
主要用于變更方案步驟編輯中。
代碼格式要求
自動化模板代碼格式要求。
例如一個名為example_template的用戶模板,代碼必須全寫在example_template這個函數里面,若有同級其他函數,引用時需要申明global。
re, json, time, datetime已經內置,可以不需要寫import。
正確示例
def func_a():
pass
def example_template():
import xxx
global func_a
def func_b():
pass
func_a()
func_b()
巡檢模板代碼格式要求。
巡檢模板代碼里面只能允許有一個可執行函數。