libslax Default Extension Libraries: bit, curl, db, os, and xutil
libslax bit Extension Library
The libslax bit extension library contains functions that create and manipulate bit strings. The functions support 64-bit integer arguments. To incorporate functions from the bit extension library into SLAX scripts, include the namespace statement for that library in the script.
ns bit extension = "http://xml.libslax.org/bit";
Call the bit extension functions using the bit
prefix and the function name. For example:
version 1.1; ns bit extension = "http://xml.libslax.org/bit"; var $a = 63; var $b = { expr "10111"; } match / { <out> { <bit-and> { <a1> bit:and("101100", "100101"); <a2> bit:and($a, $b); <a3> bit:and($a, number($b)); } <bit-or> { <a1> bit:or("101100", "100101"); <a2> bit:or($a, $b); <a3> bit:or($a, number($b)); } <bit-mask> { <a1> bit:mask(0); <a2> bit:mask(8, 32); } <ops> { <a1> bit:to-int("10101"); } } }
Table 1 lists the functions available in the bit extension library, which is supported in SLAX 1.1 scripts in Junos OS Release 12.2 and later.
Function and Arguments |
Description |
Example |
---|---|---|
|
Return the logical AND of two bit strings. |
|
|
Set the specified bit in the bit string to zero and return the new bit string. Bits are numbered starting from zero. If the integer argument is greater than the bit string length, the bit string is extended. |
|
|
Compare two values and return an integer less than, equal to, or greater than zero, if the first argument is found to be less than, equal to, or greater than the second argument, respectively. |
|
|
Return the value of the hexademical argument as a bit string. The optional second argument pads the bit string with leading zeros (0s) until it is the specified length. |
|
|
Return the value of the integer argument as a bit string. The optional second argument pads the bit string with leading zeros until it is the specified length. |
|
|
Return a bit string with the specified number of low-order bits set to one. The optional second argument pads the bit string with leading zeros until it is the specified length. |
|
|
Return the logical NAND of two bit strings. |
|
|
Return the logical NOR of two bit strings. |
|
|
Return the inversion (NOT) of a bit string. |
|
|
Return the logical OR of two bit strings. |
|
|
Set the specified bit in the bit string and return the new bit string. Bits are numbered starting from zero. If the integer argument is greater than the bit string length, the bit string is extended. |
|
|
Return the value of the bit string argument as an integer. |
|
|
Return the value of the bit string argument as a string representation of the hexadecimal value. |
|
|
Return the logical XOR of two bit strings. |
|
|
Return the logical XNOR of two bit strings. |
|
libslax curl Extension Library
- Understanding the libslax curl Extension Library
- curl:close
- curl:open
- curl:perform
- curl:set
- curl:single
- Supported Format Elements
- curl Examples
- Handling Errors
Understanding the libslax curl Extension Library
cURL is a command-line tool that uses the libcurl library and supports data transfers using a number of protocols, including FTP, FTPS, HTTP, HTTPS, SCP, and SMTP. For more information about cURL, see the cURL website at http://curl.haxx.se/.
The libslax distribution includes the curl extension library, which contains functions that perform cURL operations. To incorporate functions from the libslax curl extension library in SLAX scripts, include the namespace statement for that library in the script.
ns curl extension = "http://xml.libslax.org/curl";
You can then call the curl extension
functions using the curl
prefix and the
function name. cURL operations are directed using a set of elements
passed to the extension functions.
Table 2 lists the supported operations in the curl extension library and includes a description of each function. Table 3 and Table 4 list the supported elements and include the syntax and a description of each element. More specifically, Table 3 lists elements used for web services operations, and Table 4 lists the elements used for e-mail operations. For examples and additional information about using the curl extension library, see The curl Extension Library.
Function |
Description |
---|---|
|
Close an open connection. Further operations cannot be performed over the connection. See curl:close. |
|
Open a connection to a remote server, allowing multiple operations over a single connection. See curl:open. |
|
Perform simple transfers using a persistent connection handle
provided by |
|
Record a set of parameters that persists for the lifespan of a connection. See curl:set. |
|
Perform transfer operations without using a persistent connection. See curl:single. |
Element |
Description |
Syntax |
---|---|---|
|
Number of seconds before a connection attempt is considered to have failed. |
|
|
MIME type for the transfer payload. |
|
|
Control how HTML and XML parsing errors are handled. |
See Handling Errors |
|
Indicate that the transfer should fail if any errors, including insignificant ones, are detected. |
|
|
Specify the expected format of returned results, allowing the curl extension to automatically make the content available in the native format. Formats include "html", "name", "text", "url-encoded", and "xml". |
|
|
Provide additional header fields for the request. |
|
|
Indicate a willingness to tolerate insecure communications operations. Specifically, allow SSL Certs without checking the common name. |
|
|
Method used to transfer data. This controls the HTTP request type, as well as triggering other transfer mechanisms. Acceptable method names include "get", "post", "delete", "head", "email", "put", and "upload". "get" is the default. |
|
|
Provide additional parameter values for the request. These parameters are typically encoded into the URL. |
|
|
User's password to use for the transfer. |
|
|
Request the use of the secure version of a protocol, including HTTPS and FTPS. |
|
|
Number of seconds before an open connection is considered to have failed. |
|
|
Indicate this is a file upload request. |
|
|
Base URL for the request. |
|
|
Username to use for the transfer. |
|
|
Request detailed debug information about the operations and communication of the transfer. |
|
Element |
Description |
Syntax |
---|---|---|
|
"Cc" address for e-mail (SMTP) requests. For multiple addresses, use multiple <cc> elements. |
|
|
Contents to be transferred. |
|
|
"From" address for e-mail (SMTP) requests. |
|
|
Local hostname used for e-mail (SMTP) requests. |
|
|
Outgoing SMTP server name. Currently, MX records are not processed. |
|
|
"Subject" field for e-mail (SMTP) requests. |
|
|
"To" address for e-mail (SMTP) requests. For multiple addresses, use multiple <to> elements. |
|
The libcurl elements closely mimic the options used by the native
C libcurl API in libcurl's curl_easy_setopt()
function. Once the options are set, a call to curl_easy_perform()
performs the requested transfer. For more information about the curl_easy_setopt()
function, see http://curl.haxx.se/libcurl/c/curl_easy_setopt.html .
In the libslax curl extension
library, the libcurl API options are represented as individual elements.
For example, the <url>
element is mapped
to the CURLOPT_URL option , the <method>
element is mapped to the CURLOPT_CUSTOMREQUEST option, and so forth.
These elements can be used in three ways:
The
curl:single()
extension function supports using a set of options in a single transfer operation with no persistent connection handle.The
curl:perform()
extension function supports using a set of options with a persistent connection handle. The handle is returned from thecurl:open()
extension function and can be closed with thecurl:close()
extension function.The
curl:set()
extension function records a set of options for a connection handle and keeps those options active for the lifetime of the connection. For example, if the script needs to transfer a number of files, it can record the<username>
and<password>
options and avoid repeating them in everycurl:perform()
call.
curl:close
The curl:close()
extension function
closes an open connection. Further operations cannot be performed
over the connection once it is closed.
The syntax is:
node-set[empty] curl:close(node-set[connection]);
The argument is the connection handle to close.
curl:open
The curl:open()
extension function
opens a connection to a remote server, allowing multiple operations
over a single connection.
The syntax is:
node-set[connection] curl:open();
The returned object is a connection handle that can be passed
to curl:perform()
or curl:close()
.
curl:perform
The curl:perform()
extension function
performs simple transfers using a persistent connection handle provided
by curl:open()
.
The syntax is:
node-set[object] curl:perform(node-set[connection], node-set[options])
The arguments are the connection handle and a set of option elements. Supported curl extension library elements are defined in Table 3 and Table 4.
The returned object is an XML hierarchy containing the results
of the transfer. Table 5 lists the possible elements in the reply, and Table 6 lists the possible
elements contained within the <header>
element.
Element |
Contents |
---|---|
|
Empty element which Indicates success |
|
Parsed data |
|
Error message text, if any |
|
Parsed header fields |
|
Raw data from the reply |
|
Raw header fields from the reply |
|
Requested URL |
Element |
Contents |
---|---|
|
HTTP reply code |
|
HTTP reply field (with @name and value) |
|
HTTP reply message |
|
HTTP reply version string |
The following example shows the <header>
element with header fields parsed into <field>
elements:
<header> <version>HTTP/1.1</version> <code>404</code> <message>Not Found</message> <field name="Content-Type">text/html</field> <field name="Content-Length">345</field> <field name="Date">Mon, 08 Aug 2011 03:40:21 GMT</field> <field name="Server">lighttpd/1.4.28 juisebox</field> </header>
curl:set
The curl:set()
extension function
records a set of parameters that persist for the lifespan of a connection.
The syntax is:
node-set[empty] curl:set(node-set[handle], node-set[options]);
The arguments are the connection handle and a set of option elements. Supported curl extension library elements are defined in Table 3 and Table 4.
curl:single
The curl:single()
extension function
performs transfer operations without using a persistent connection.
The syntax is:
node-set[result] curl:single(node-set[options]);
The returned object is identical in structure to the one returned
by curl:perform()
. Refer to curl:perform for additional information.
Supported Format Elements
Starting with version 1.2 of the SLAX language, which is supported
in Junos OS Release 14.2 and later releases, the format
element supports two new formats in addition to "html", "text",
and "xml": "name" and "url-encoded". The "name" encoding is used for
name=value pairs that are separated by newlines, whereas the "url-encoded"
encoding is used when the name=value pairs are separated by an ampersand
(&).
The parsed data is returned in the <data>
element, using <name>
elements. In
the following example, format
is set to
"url-encoded":
<results> <url>http://api.example.com/request_token</url> <curl-success/> <raw-headers>HTTP/1.1 200 OK
 Server: XXXX
 Date: Tue, 18 Jun 2013 18:56:31 GMT
 Content-Type: application/x-www-form-urlencoded
 Transfer-Encoding: chunked
 Connection: keep-alive
 x-server-response-time: 69
 x-example-request-id: 123456
 pragma: no-cache
 cache-control: no-cache
 x-http-protocol: None
 x-frame-options: SAMEORIGIN
 X-RequestId: 12345
 
 </raw-headers> <headers> <version>HTTP/1.1</version> <code>200</code> <message>OK</message> <header name="Server">XXXXX</header> <header name="Date">Tue, 18 Jun 2013 18:56:31 GMT</header> <header name="Content-Type" >application/x-www-form-urlencoded</header> <header name="Transfer-Encoding">chunked</header> <header name="Connection">keep-alive</header> <header name="x-server-response-time">69</header> <header name="x-example-request-id">123456</header> <header name="pragma">no-cache</header> <header name="cache-control">no-cache</header> <header name="x-http-protocol">None</header> <header name="x-frame-options">SAMEORIGIN</header> <header name="X-RequestId">12345</header> </headers> <raw-data>oauth_token_secret=s&oauth_token=t</raw-data> <data format="url-encoded"> <name name="oauth_token_secret">s</name> <name name="oauth_token">t</name> </data> </results>
curl Examples
The following examples show SLAX scripts that use the libslax curl
extension library functions to perform operations.
The following SLAX script performs a simple GET operation to retrieve a web page. The script specifies the header field for the HTTP header and a parameter that is incorporated into the requested URL.
version 1.1; ns curl extension = "http://xml.libslax.org/curl"; param $url = "http://www.juniper.net"; match / { <op-script-results> { var $options = { <header name="client"> "slaxproc"; <param name="smokey"> "bandit"; } var $results = curl:single($url, $options); message "completed: " _ $results/headers/message; <curl> { copy-of $results; } } }
The following SLAX script sends an e-mail by way of a server, which is provided as a parameter:
version 1.1; ns curl extension = "http://xml.libslax.org/curl"; param $server; match / { <out> { var $info = { <method> "email"; <server> $server; <from> "muffin@example.com"; <to> "phil@example.net"; <subject> "Testing..."; <contents> "Hello, This is an email. Thanks, Phil "; } var $res = curl:single($info); <res> { copy-of $res; } } }
The following SLAX op script uses the provided credentials to connect and log in to a web application:
version 1.2; ns curl extension = "http://xml.libslax.org/curl"; param $url = "http://198.51.100.10:4000/login"; param $username = "admin"; param $password = "password"; var $params := { <url> $url; <method> "post"; <insecure>; <param name="username"> $username; <param name="password"> $password; } main <top> { var $curl = curl:open(); var $data = curl:perform($curl, $params); copy-of $data; expr curl:close($curl); }
You can use Flask to create a simple web application to test the script. Flask, which is available on PyPI, is a lightweight Web Server Gateway Interface (WSGI) web application framework. The following Python script from https://pythonspot.com/login-authentication-with-flask creates a simple web application with a login page.
from flask import Flask from flask import Flask, flash, redirect, render_template, request, session, abort import os app = Flask(__name__) @app.route('/') def home(): if not session.get('logged_in'): return render_template('login.html') else: return "Hello Boss!" @app.route('/login', methods=['POST']) def do_admin_login(): if request.form['password'] == 'password' and request.form['username'] == 'admin': session['logged_in'] = True else: flash('wrong password!') return home() if __name__ == "__main__": app.secret_key = os.urandom(12) app.run(debug=True,host='0,0.0.0', port=4000)
To test the op script, first start the web application script on the remote device.
user@nms:~$ python3 app.py * Serving Flask app "app" (lazy loading) ...
Then enable and run the op script on the device running Junos OS. The results are logged to the op-script.log file.
user@router> op curl-test user@router> show log op-script.log | last 100 ... <?xml version="1.0"?> <top> <results> <url>http://198.51.100.10:4000/login</url> <curl-success/> <raw-headers>HTTP/1.0 200 OK
 Content-Type: text/html; charset=utf-8
 Content-Length: 11
 Vary: Cookie
 Set-Cookie: session=eyJsb2dnZWRfaW4iOnRydWV9.XzxdUg.wm2A58ct6twASerlHjuQ64nwaiI; HttpOnly; Path=/
 Server: Werkzeug/1.0.1 Python/3.6.9
 Date: Tue, 18 Aug 2020 22:59:30 GMT
 
 </raw-headers> <headers> <version>HTTP/1.0</version> <code>200</code> <message>OK</message> <header name="Content-Type">text/html; charset=utf-8</header> <header name="Content-Length">11</header> <header name="Vary">Cookie</header> <header name="Set-Cookie">session=eyJsb2dnZWRfaW4iOnRydWV9.XzxdUg.wm2A58ct6twASerlHjuQ64nwaiI; HttpOnly; Path=/</header> <header name="Server">Werkzeug/1.0.1 Python/3.6.9</header> <header name="Date">Tue, 18 Aug 2020 22:59:30 GMT</header> </headers> <raw-data>Hello Boss!</raw-data> </results>Aug 18 15:59:31 end dump </top> ...
Handling Errors
Starting with version 1.2 of the SLAX language, which is supported
in Junos OS Release 14.2 and later releases, you can use the <errors>
element to control the handling of HTML
and XML parsing errors. The default behavior is to display errors
in the standard error output stream (stderr). By supplying different
values for the <errors>
element, you
can also choose to ignore, log, or record the error. Table 7 lists the values that you can
use for the errors
element.
Value |
Special Behavior |
---|---|
default |
Errors are displayed on stderr |
ignore |
Errors are discarded |
log |
Errors are logged (via slaxLog()) |
record |
Errors are recorded |
When the value of <errors>
is
set to "record", all errors appear in a string under the <errors>
element in the XML node (as returned, for
example by curl:perform
). If no errors
are generated, the <errors>
element
is not present, which can be used as a test for errors.
var $opt = { <url> $url; <format> "html"; <errors> "record"; } var $res = curl:single($opts); if ($res/errors) { terminate "failure: " _ $res/errors; }
libslax db Extension Library
The libslax db extension library, which is supported in Junos OS Release 17.4R1 and later, provides a way for SLAX scripts to store, manipulate, retrieve and delete data stored in a database. To use functions from the db extension library in SLAX scripts, include the namespace statement for that library in the script.
ns db extension = "http://xml.libslax.org/db";
Table 8 summarizes the functions that are available in the db extension library. For examples and additional information about the db extension functions, see db Extension Functions.
Function |
Description |
---|---|
|
Close the database connection and free all the structures associated with previous operations performed on this handle. |
|
Create a collection in the database associated with the open database handle using the given field information. |
|
Delete instances in a collection that match the given conditions in the database associated with the open database handle. |
|
Fetch a result instance using the cursor returned from
a |
|
Return a cursor to the result set for instances matching
the given conditions. |
|
Find and read all the instances matching the given conditions. |
|
Insert data into a collection in the database associated with the open database handle. |
|
Open a database connection using the provided options, which include the back-end database engine and the database name. |
|
Run a custom query. |
|
Update a set of instances matching the given conditions with the provided instance. |
Table 9 summarizes the elements that can be used in the options and data of db extensions functions. For examples and additional information about db elements, see db Elements.
Element |
Description |
Example |
---|---|---|
|
Specify the data collection on which to perform operations. This corresponds to a SQL database table. |
<collection> "employee"; |
|
Specify a condition that must be satisfied when operating with data instances from the datastore. This forms the condition used with the WHERE clause when operating with a SQL datastore. Mandatory elements include:
|
<condition> { <selector> "id; <operator> "in"; <value> "(1, 10)"; } |
|
Specify multiple conditions with |
<conditions> { <and> { <condition> { ... /* c1 */ } <condition> { ... /* c2 */ } <or> { <condition> { ... /* c3 */ } <condition> { ... /* c4 */ } } } } |
|
Specify the name of the database on which to operate. |
<database> "test.db"; |
|
Specify the back-end database engine that is used to store and access data. |
<engine> "sqlite"; |
|
Define the metadata for each field in the collection. |
<field> { <name> "name"; <type> "integer"; <primary>; } |
|
Specify metadata about fields in a collection using |
<fields> { <field> { ... } } |
|
Represent a single instance in a collection when inserting or manipulating data in the datastore. The element contains fields and their corresponding values in that record. |
<instance> { <id> 5; <name> "John"; } |
|
Define multiple instances in a collection when inserting or manipulating data in the datastore. |
<instances> { <instance> { ... ... } ... } |
|
Limit the number of instances that a result can contain. |
<limit> 10; |
|
Output node returned from most of the db extension functions. This node contains a |
<result> { <status> { <ok> } } |
|
Specify only the fields that should appear as part of the result set when querying the datastore. |
<retrieve> { <id>; <name>; } |
|
Skip over a specified number of instances in the result set before returning to the user. |
<skip> 5; |
|
Specify the fields and the order by which the result set must be sorted. Specify the fields by including the |
<sort> { <by> "id"; <by> "age"; <order> "desc"; } |
libslax os Extension Library
The libslax os
extension library
provides a set of functions to invoke operating system-related operations
on the local host. To use functions from the os
extension library in SLAX scripts, include the namespace statement
for that library in the script.
ns os extension = "http://xml.libslax.org/os";
Table 10 summarizes
the functions that are available in the os extension library. The
return value of many os
extension functions
consists of a set of zero or more error nodes. Each node can contain
an <error>
element with additional child
elements. For examples and additional information about os
extension functions, see os Extension Functions.
Function |
Description |
First Supported Junos OS Release |
---|---|---|
|
Change the permissions of one or more files. |
17.4 |
|
Change the file owner and group for one or more files. |
17.4 |
|
Set the exit code for the process running the script. |
14.1 |
|
Create a new directory with the specified name, path, and permissions. The |
14.1 |
|
Delete a file or empty directory. |
17.4 |
|
Return information about files and directories in a node-set
of |
14.1 |
|
Return a |
17.4 |
libslax xutil Extension Library
The libslax xutil extension library contains functions that convert between strings and XML node sets. To incorporate functions from the xutil extension library into SLAX scripts, include the namespace statement for that library in the script.
ns xutil extension = "http://xml.libslax.org/xutil";
Call the xutil extension functions using the xutil prefix and the function name. Table 11 lists the functions available in the xutil extension library, which are supported in SLAX 1.1 and later scripts. For examples and additional information about xutil extension functions, see xutil Extension Functions.
Function and Arguments |
Description |
First Supported Junos OS Release |
---|---|---|
|
Convert a string containing JSON data into the native representation of that data in XML. |
14.2 |
|
Limit the depth of recursive calls. The default limit is 3000. |
14.1 |
|
Convert a string containing XML data into the native representation of that data. |
12.2 |
|
Convert XML data into a string containing JSON data. This function encodes tags as JSON objects inside a string. |
14.2 |
|
Convert XML data into a string. |
12.2 |