YANG工具的开源:PYANG安装方法

PYANG项目介绍

PYANG是个github上的开源项目。作者是Martin Bjorklund。NETCONF、YANG的RFC都是这哥么写的,还是唯一作者,其他人只是“有贡献”。有多牛叉不用说了吧。他的名字就是权威。
项目链接:https://github.com/mbj4668/pyang
这哥们的github账号有点山寨。大家忽略。

PYANG的功能

PYANG支持的功能如下:

  • Validate YANG modules.
    验证YANG模块。
  • Convert YANG modules to YIN, and YIN to YANG.
    YIN/YANG转换。
  • Translate YANG data models to DSDL schemas, which can be used for validating various XML instance documents.
    将 YANG 数据模型转换为 DSDL 模式,可用于验证各种 XML 实例文档。
  • Generate UML diagrams from YANG models.
    从 YANG 模型生成 UML 图。
  • Generate compact tree representation of YANG models for quick visualization.
    生成YANG tree,以便于YANG的快速可视化。
  • Generate a skeleton XML instance document from the data model.
    从数据模型生成框架 XML 实例文档。
  • Schema-aware translation of instance documents encoded in XML to JSON and vice-versa.
    将用 XML 编码的实例文档的模式感知转换为 JSON。
  • Plugin framework for simple development of other outputs, such as code generation.
    用于简单开发其他输出的插件框架,例如代码生成。

本人最常用的几个功能是:YANG语法白盒验证、YIN/YANG转换、YANG tree可视化。YANG/XSD模型转化、YANG模型UML生成用的比较少。PYANG可以作为其他开发的框架插件,YANG语法白盒检查很容易包装成定时任务,用于每天检查自己项目代码中的YANG模型语法问题。

PYANG安装方法

上面项目链接中的README.md讲的比较详细,但是稍微有点小问题。我把我的成功安装经验介绍一下。如果你不会安装或者出错不知道如何处理,可以试试我的本地安装方法。

下载项目源码

进入项目链接:https://github.com/mbj4668/pyang。下载全量源码。你可以git clone;有的公司可能有权限管理,也可以像我一样,直接download zip。
在这里插入图片描述

源码解压缩

下载源码后,建议解压到一个全英文的目录下。方便后面操作。

本地安装

进入源码目录:

在这里插入图片描述

执行:pip install -e .

注意这里是在项目根目录下执行。README.md中是错误的。
在这里插入图片描述
这样就安装成功了。我安装的版本是pyang-2.5.3

检查安装结果:pyang -v

在这里插入图片描述

查看帮助信息:pyang -h

Options:
-h, --help Show this help message and exit
-v, --version Show version number and exit
-V, --verbose
-e, --list-errors Print a listing of all error and warning codes and
exit.
–print-error-code On errors, print the error code instead of the error
message.
–print-error-basename
On errors, print the basename of files of the error
message.
–msg-template=MSG_TEMPLATE
Template used to display error messages. This is a
python new-style format string used to format the
message information with keys file, line, code, type
and msg. Example: --msg-template=‘{file} || {line} ||
{code} || {type} || {level} || {msg}’
-W WARNING If WARNING is ‘error’, treat all warnings as errors,
except any listed WARNING. If WARNING is ‘none’, do
not report any warnings.
-E WARNING Treat each WARNING as an error. For a list of
warnings, use --list-errors.
–ignore-error=ERROR Ignore ERROR. Use with care. For a list of errors,
use --list-errors.
–ignore-errors Ignore all errors. Use with care.
–canonical Validate the module(s) according to the canonical YANG
order.
–verify-revision-history
Ensure that all old revisions in the revision history
can be found in the module search path.
–max-line-length=MAX_LINE_LEN
–max-identifier-length=MAX_IDENTIFIER_LEN
-t TRANSFORMS, --transform=TRANSFORMS
Apply transform TRANSFORM. Supported transforms are:
edit
-f FORMAT, --format=FORMAT
Convert to FORMAT. Supported formats are: yang, yin,
dsdl, capability, depend, flatten, identifiers,
jsonxsl, jstree, jtox, name, omni, sample-xml-
skeleton, tree, uml
-o OUTFILE, --output=OUTFILE
Write the output to OUTFILE instead of stdout.
-F FEATURES, --features=FEATURES
Features to support, default all.
:[,]*
-X EXCLUDE_FEATURES, --exclude-features=EXCLUDE_FEATURES
Features not to support, default none.
:[,]*
–max-status=MAXSTATUS
Max status to support, one of: current, deprecated,
obsolete
–deviation-module=DEVIATION
Deviation module
-p PATH, --path=PATH ;-separated search path for yin and yang modules
–plugindir=PLUGINDIR
Load pyang plugins from PLUGINDIR
–strict Force strict YANG compliance.
–lax-quote-checks Lax check of backslash in quoted strings.
–lax-xpath-checks Lax check of XPath expressions.
–trim-yin In YIN input modules, trim whitespace in textual
arguments.
-L, --hello Filename of a server’s hello message is given instead
of module filename(s).
–implicit-hello-deviations
Attempt to parse all deviations from hello message
regardless of declaration.
–keep-comments Pyang will not discard comments;
has effect if the output plugin can
handle comments.
–no-path-recurse Do not recurse into directories in the
yang path.
–bbf Validate the module(s) according to BBF rules.
–check-update-from=OLDMODULE
Verify that upgrade from OLDMODULE follows RFC 6020
and 7950 rules.
-P OLD_PATH, --check-update-from-path=OLD_PATH
;-separated search path for yin and yang modules used
by OLDMODULE
-D OLD_DEVIATION, --check-update-from-deviation-module=OLD_DEVIATION
Old deviation module of the OLDMODULE. This option can
be given multiple times.
–check-update-include-structures
Check sx:structures.
–ieee Validate the module(s) according to IEEE rules.
–ietf Validate the module(s) according to IETF rules.
–ietf-help Print help on the IETF checks and exit
–lint Validate the module(s) according to RFC 8407rules.
–lint-namespace-prefix=LINT_NAMESPACE_PREFIXES
Validate that the module’s namespace matches one of
the given prefixes.
–lint-modulename-prefix=LINT_MODULENAME_PREFIXES
Validate that the module’s name matches one of the
given prefixes.
–lint-ensure-hyphenated-names
No upper case and underscore in names.
–mef Validate the module(s) according to MEF rules.
–3gpp Validate the module(s) according to 3GPP rules.

YANG output specific options:
–yang-canonical Print in canonical order
–yang-remove-unused-imports
–yang-remove-comments
–yang-line-length=YANG_LINE_LENGTH
Maximum line length

YIN output specific options:
–yin-canonical Print in canonical order
–yin-pretty-strings
Pretty print strings

Hybrid DSDL schema output specific options:
–dsdl-no-documentation
No output of DTD compatibility documentation
annotations
–dsdl-no-dublin-core
No output of Dublin Core metadata annotations
–dsdl-record-defs Record all top-level defs (even if not used)
–dsdl-lax-yang-version
Try to translate modules with unsupported YANG
versions (use at own risk)

Capability output specific options:
–capability-entity
Write ampersands as XML entity

Depend output specific options:
–depend-target=DEPEND_TARGET
Makefile rule target
–depend-no-submodules
Do not generate dependencies for included submodules
–depend-from-submodules
Generate dependencies from included submodules
–depend-recurse Generate dependencies to all imports, recursively
–depend-extension=DEPEND_EXTENSION
YANG module file name extension
–depend-include-path
Include file path in the prerequisites
–depend-ignore-module=DEPEND_IGNORE
(sub)module to ignore in the prerequisites. This
option can be given multiple times.

Flatten output specific options:
–flatten-no-header
Do not emit the CSV header.
–flatten-keyword Output the keyword.
–flatten-type Output the top-level type.
–flatten-primitive-type
Output the primitive type.
–flatten-flag Output flag property.
–flatten-description
Output the description.
–flatten-keys Output the key names if specified.
–flatten-keys-in-xpath
Output the XPath with keys in path.
–flatten-prefix-in-xpath
Output the XPath with prefixes instead of modules.
–flatten-qualified-in-xpath
Output the XPath with qualified in path
/module1:root/module1:node/module2:node/…
–flatten-qualified-module-and-prefix-path
Output an XPath with both module and prefix i.e.
/module1:prefix1:root/…
–flatten-deviated Output deviated nodes.
–flatten-data-keywords
Flatten all data keywords instead of onlydata
definition keywords.
–flatten-filter-keyword=FLATTEN_FILTER_KEYWORD
Filter output to only desired keywords.
–flatten-filter-primitive=FLATTEN_FILTER_PRIMITIVE
Filter output to only desired primitive types.
–flatten-filter-flag=FLATTEN_FILTER_FLAG
Filter output to flags.
–flatten-csv-dialect=FLATTEN_CSV_DIALECT
CSV dialect for output.
–flatten-ignore-no-primitive
Ignore error if primitive is missing.
–flatten-status Output the status statement value.
–flatten-resolve-leafref
Output the XPath of the leafref target.

JSTree output specific options:
–jstree-no-path Do not include paths to make
page less wide
–jstree-path=JSTREE_PATH
Subtree to print

Name output specific options:
–name-print-revision
Print the name and revision in name@revision format

OmniGraffle output specific options:
–omni-path=OMNI_TREE_PATH
Subtree to print

Sample-xml-skeleton output specific options:
–sample-xml-skeleton-doctype=DOCTYPE
Type of sample XML document (data or config).
–sample-xml-skeleton-defaults
Insert leafs with defaults values.
–sample-xml-skeleton-annotations
Add annotations as XML comments.
–sample-xml-skeleton-path=SAMPLE_PATH
Subtree to print

SID file specific options:
–sid-help Print help on automatic SID generation
–sid-generate-file=GENERATE_SID_FILE
Generate a .sid file.
–sid-update-file=UPDATE_SID_FILE
Generate a .sid file based on a previous .sid file.
–sid-check-file=CHECK_SID_FILE
Check the consistency between a .sid file and the
.yang file(s).
–sid-list Print the list of SID.
–sid-finalize Mark current allocations as non-provisional.
–sid-registration-info
Print the information required by the SID registry.
–sid-extra-range=EXTRA_SID_RANGE
Add an extra SID range during a .sid file update.

Tree output specific options:
–tree-help Print help on tree symbols and exit
–tree-depth=TREE_DEPTH
Number of levels to print
–tree-line-length=TREE_LINE_LENGTH
Maximum line length
–tree-path=TREE_PATH
Subtree to print
–tree-print-groupings
Print groupings
–tree-no-expand-uses
Do not expand uses of groupings
–tree-module-name-prefix
Prefix with module names instead of prefixes
–tree-print-yang-data
Print ietf-restconf:yang-data structures
–tree-print-structures
Print ietf-yang-structure-ext:structure

UML specific options:
–uml-classes-only Generate UML with classes only, no attributes
–uml-split-pages=UML_PAGES_LAYOUT
Generate UML output split into pages (separate .png
files), NxN, example 2x2
–uml-output-directory=UML_OUTPUTDIR
Put generated .png or .png file(s)<br/> in OUTPUTDIR (default img/)<br/> –uml-title=UML_TITLE<br/> Set the title of the generated UML, including the<br/> output file name<br/> –uml-header=UML_HEADER<br/> Set the page header of the generated UML<br/> –uml-footer=UML_FOOTER<br/> Set the page footer of the generated UML<br/> –uml-long-identifiers<br/> Use the full schema identifiers for UML class names.<br/> –uml-inline-groupings<br/> Inline groupings where they are used.<br/> –uml-inline-augments<br/> Inline augmentations where they are used.<br/> –uml-description Include description of structural nodes in diagram.<br/> –uml-no=UML_NO Suppress parts of the diagram. Valid suppress values<br/> are: module, uses, leafref, identity, identityref,<br/> typedef, import, annotation, circles, stereotypes.<br/> Annotations suppresses YANG constructs represented as<br/> annotations such as config statements for containers<br/> and module info. Module suppresses module box around<br/> the diagram and module information. Example --uml-<br/> no=circles,stereotypes,typedef,import<br/> –uml-truncate=UML_TRUNCATE<br/> Leafref attributes and augment elements can have long<br/> paths making the classes too wide. This option will<br/> only show the tail of the path. Example --uml-<br/> truncate=augment,leafref<br/> –uml-max-enums=UML_MAX_ENUMS<br/> The maximum number of enumerated values being rendered<br/> –uml-filter Generate filter file, comment out lines with ‘-’ and<br/> use with option ‘–filter-file’ to filter the UML<br/> diagram<br/> –uml-filter-file=UML_FILTER_FILE<br/> NOT IMPLEMENTED: Only paths in the filter file will be<br/> included in the diagram

Edit transform specific options:
–edit-yang-version=VERSION
Set YANG version to the supplied value
–edit-namespace=NAMESPACE
Set YANG namespace to the supplied value
–edit-update-import-dates
Set import/include revision-date statements to match
imported/included modules/submodules
–edit-delete-import-dates
Delete import/include revision-date statements
–edit-organization=ORGANIZATION
Set module/submodule organization to the supplied
value
–edit-contact=CONTACT
Set module/submodule contact to the supplied value
–edit-description=DESCRIPTION
Set module/submodule description to the supplied value
–edit-delete-revisions-after=PREVDATE
Delete any revisions after the supplied yyyy-mm-dd
–edit-revision-date=DATE
Set most recent revision date to the supplied yyyy-mm-
dd
–edit-revision-description=DESCRIPTION
Set most recent revision description to the supplied
value
–edit-revision-reference=REFERENCE
Set most recent revision reference to the supplied
value

常见用法

这里讲我常用的几个命令。如果想研究哪个功能不知道用什么命令,可以发评论区,我们一起研究试试。

YANG语法验证

最基本的命令是pyang --lint xxx.yang,一般YANG模型放在modules目录下。pyang会内置一些标准YANG。

pyang --lint  modules\ietf\ietf-inet-types.yang

有错的话,会直接报错的。比如:我构造了一个枚举的typdef下存在两个相同的value值。
在这里插入图片描述
则报错如下:
在这里插入图片描述

YIN/YANG转换

//YANG转YIN
pyang -f yin -o ietf-yang-types.yin ietf-yang-types.yang
//YIN转YANG
pyang -f yang -o ietf-yang-types.yang ietf-yang-types.yin

YANG tree可视化

pyang -f tree modules\ietf\ietf-interfaces.yang -o ietf-interfaces.txt

转换出来的YANG tree大概是这个样子的:

module: ietf-interfaces
  +--rw interfaces                            //rw是config true;ro是config false
  |  +--rw interface* [name]                         //*表示list,[]中的是key
  |     +--rw name                        string
  |     +--rw description?                string     //?是可选节点,不带?是必选节点
  |     +--rw type                        identityref
  |     +--rw link-up-down-trap-enable?   enumeration {if-mib}?   // {if-mib}? 是if-feature
  |     +--ro oper-status                 enumeration
  |     +--ro last-change?                yang:date-and-time
  x--ro interfaces-state                // x是deprecated节点,不推荐使用的节点
     x--ro interface* [name]
        x--ro name               string
        x--ro type               identityref
        x--ro admin-status       enumeration {if-mib}?
        x--ro oper-status        enumeration
        x--ro last-change?       yang:date-and-time
        x--ro if-index           int32 {if-mib}?
        x--ro phys-address?      yang:phys-address
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值