From 582459d6d30875dc1b224688905702b1fcbc0766 Mon Sep 17 00:00:00 2001
From: Fede Luzzi
Date: Thu, 30 Jan 2025 17:39:56 -0300
Subject: [PATCH] bug fix docker
---
connpy/_version.py | 2 +-
connpy/core.py | 2 +-
docs/connpy/index.html | 1206 +++++++++++++---------------------------
3 files changed, 388 insertions(+), 822 deletions(-)
diff --git a/connpy/_version.py b/connpy/_version.py
index 52e5ccb..be7f34f 100644
--- a/connpy/_version.py
+++ b/connpy/_version.py
@@ -1,2 +1,2 @@
-__version__ = "4.1.1"
+__version__ = "4.1.2"
diff --git a/connpy/core.py b/connpy/core.py
index 9f2ce96..77c5685 100755
--- a/connpy/core.py
+++ b/connpy/core.py
@@ -596,7 +596,7 @@ class node:
if results in initial_indices[self.protocol]:
if self.protocol in ["ssh", "sftp"]:
child.sendline('yes')
- elif self.protocol in ["telnet", "kubectl"]:
+ elif self.protocol in ["telnet", "kubectl", "docker"]:
if self.user:
child.sendline(self.user)
else:
diff --git a/docs/connpy/index.html b/docs/connpy/index.html
index 7ad08da..d8713ce 100644
--- a/docs/connpy/index.html
+++ b/docs/connpy/index.html
@@ -2,18 +2,32 @@
-
-
+
+
connpy API documentation
-
-
-
-
-
-
+
+
+
+
+
+
-
-
+
+
@@ -424,453 +438,6 @@ input = "go to router 1 and get me the full configuration"
result = myia.ask(input, dryrun = False)
print(result)
-
-
-Expand source code
-
-
#!/usr/bin/env python3
-'''
-## Connection manager
-
-Connpy is a SSH, SFTP, Telnet, kubectl, and Docker pod connection manager and automation module for Linux, Mac, and Docker.
-
-### Features
- - Manage connections using SSH, SFTP, Telnet, kubectl, and Docker exec.
- - Set contexts to manage specific nodes from specific contexts (work/home/clients/etc).
- - You can generate profiles and reference them from nodes using @profilename so you don't
- need to edit multiple nodes when changing passwords or other information.
- - Nodes can be stored on @folder or @subfolder@folder to organize your devices. They can
- be referenced using node@subfolder@folder or node@folder.
- - If you have too many nodes, get a completion script using: conn config --completion.
- Or use fzf by installing pyfzf and running conn config --fzf true.
- - Create in bulk, copy, move, export, and import nodes for easy management.
- - Run automation scripts on network devices.
- - Use GPT AI to help you manage your devices.
- - Add plugins with your own scripts.
- - Much more!
-
-### Usage
-```
-usage: conn [-h] [--add | --del | --mod | --show | --debug] [node|folder] [--sftp]
- conn {profile,move,mv,copy,cp,list,ls,bulk,export,import,ai,run,api,plugin,config,sync,context} ...
-
-positional arguments:
- node|folder node[@subfolder][@folder]
- Connect to specific node or show all matching nodes
- [@subfolder][@folder]
- Show all available connections globally or in specified path
-
-options:
- -h, --help show this help message and exit
- -v, --version Show version
- -a, --add Add new node[@subfolder][@folder] or [@subfolder]@folder
- -r, --del, --rm Delete node[@subfolder][@folder] or [@subfolder]@folder
- -e, --mod, --edit Modify node[@subfolder][@folder]
- -s, --show Show node[@subfolder][@folder]
- -d, --debug Display all conections steps
- -t, --sftp Connects using sftp instead of ssh
-
-Commands:
- profile Manage profiles
- move(mv) Move node
- copy(cp) Copy node
- list(ls) List profiles, nodes or folders
- bulk Add nodes in bulk
- export Export connection folder to Yaml file
- import Import connection folder to config from Yaml file
- ai Make request to an AI
- run Run scripts or commands on nodes
- api Start and stop connpy api
- plugin Manage plugins
- config Manage app config
- sync Sync config with Google
- context Manage contexts with regex matching
-```
-
-### Manage profiles
-```
-usage: conn profile [-h] (--add | --del | --mod | --show) profile
-
-positional arguments:
- profile Name of profile to manage
-
-options:
- -h, --help show this help message and exit
- -a, --add Add new profile
- -r, --del, --rm Delete profile
- -e, --mod, --edit Modify profile
- -s, --show Show profile
-
-```
-
-### Examples
-```
- #Add new profile
- conn profile --add office-user
- #Add new folder
- conn --add @office
- #Add new subfolder
- conn --add @datacenter@office
- #Add node to subfolder
- conn --add server@datacenter@office
- #Add node to folder
- conn --add pc@office
- #Show node information
- conn --show server@datacenter@office
- #Connect to nodes
- conn pc@office
- conn server
- #Create and set new context
- conn context -a office .*@office
- conn context --set office
- #Run a command in a node
- conn run server ls -la
-```
-## Plugin Requirements for Connpy
-### General Structure
-- The plugin script must be a Python file.
-- Only the following top-level elements are allowed in the plugin script:
- - Class definitions
- - Function definitions
- - Import statements
- - The `if __name__ == "__main__":` block for standalone execution
- - Pass statements
-
-### Specific Class Requirements
-- The plugin script must define specific classes with particular attributes and methods. Each class serves a distinct role within the plugin's architecture:
- 1. **Class `Parser`**:
- - **Purpose**: Handles parsing of command-line arguments.
- - **Requirements**:
- - Must contain only one method: `__init__`.
- - The `__init__` method must initialize at least two attributes:
- - `self.parser`: An instance of `argparse.ArgumentParser`.
- - `self.description`: A string containing the description of the parser.
- 2. **Class `Entrypoint`**:
- - **Purpose**: Acts as the entry point for plugin execution, utilizing parsed arguments and integrating with the main application.
- - **Requirements**:
- - Must have an `__init__` method that accepts exactly three parameters besides `self`:
- - `args`: Arguments passed to the plugin.
- - The parser instance (typically `self.parser` from the `Parser` class).
- - The Connapp instance to interact with the Connpy app.
- 3. **Class `Preload`**:
- - **Purpose**: Performs any necessary preliminary setup or configuration independent of the main parsing and entry logic.
- - **Requirements**:
- - Contains at least an `__init__` method that accepts parameter connapp besides `self`.
-
-### Class Dependencies and Combinations
-- **Dependencies**:
- - `Parser` and `Entrypoint` are interdependent and must both be present if one is included.
- - `Preload` is independent and may exist alone or alongside the other classes.
-- **Valid Combinations**:
- - `Parser` and `Entrypoint` together.
- - `Preload` alone.
- - All three classes (`Parser`, `Entrypoint`, `Preload`).
-
-### Preload Modifications and Hooks
-
-In the `Preload` class of the plugin system, you have the ability to customize the behavior of existing classes and methods within the application through a robust hooking system. This documentation explains how to use the `modify`, `register_pre_hook`, and `register_post_hook` methods to tailor plugin functionality to your needs.
-
-#### Modifying Classes with `modify`
-The `modify` method allows you to alter instances of a class at the time they are created or after their creation. This is particularly useful for setting or modifying configuration settings, altering default behaviors, or adding new functionalities to existing classes without changing the original class definitions.
-
-- **Usage**: Modify a class to include additional configurations or changes
-- **Modify Method Signature**:
- - `modify(modification_method)`: A function that is invoked with an instance of the class as its argument. This function should perform any modifications directly on this instance.
-- **Modification Method Signature**:
- - **Arguments**:
- - `cls`: This function accepts a single argument, the class instance, which it then modifies.
- - **Modifiable Classes**:
- - `connapp.config`
- - `connapp.node`
- - `connapp.nodes`
- - `connapp.ai`
- - ```python
- def modify_config(cls):
- # Example modification: adding a new attribute or modifying an existing one
- cls.new_attribute = 'New Value'
-
- class Preload:
- def __init__(self, connapp):
- # Applying modification to the config class instance
- connapp.config.modify(modify_config)
- ```
-
-#### Implementing Method Hooks
-There are 2 methods that allows you to define custom logic to be executed before (`register_pre_hook`) or after (`register_post_hook`) the main logic of a method. This is particularly useful for logging, auditing, preprocessing inputs, postprocessing outputs or adding functionalities.
-
- - **Usage**: Register hooks to methods to execute additional logic before or after the main method execution.
-- **Registration Methods Signature**:
- - `register_pre_hook(pre_hook_method)`: A function that is invoked before the main method is executed. This function should do preprocessing of the arguments.
- - `register_post_hook(post_hook_method)`: A function that is invoked after the main method is executed. This function should do postprocessing of the outputs.
-- **Method Signatures for Pre-Hooks**
- - `pre_hook_method(*args, **kwargs)`
- - **Arguments**:
- - `*args`, `**kwargs`: The arguments and keyword arguments that will be passed to the method being hooked. The pre-hook function has the opportunity to inspect and modify these arguments before they are passed to the main method.
- - **Return**:
- - Must return a tuple `(args, kwargs)`, which will be used as the new arguments for the main method. If the original arguments are not modified, the function should return them as received.
-- **Method Signatures for Post-Hooks**:
- - `post_hook_method(*args, **kwargs)`
- - **Arguments**:
- - `*args`, `**kwargs`: The arguments and keyword arguments that were passed to the main method.
- - `kwargs["result"]`: The value returned by the main method. This allows the post-hook to inspect and even alter the result before it is returned to the original caller.
- - **Return**:
- - Can return a modified result, which will replace the original result of the main method, or simply return `kwargs["result"]` to return the original method result.
- - ```python
- def pre_processing_hook(*args, **kwargs):
- print("Pre-processing logic here")
- # Modify arguments or perform any checks
- return args, kwargs # Return modified or unmodified args and kwargs
-
- def post_processing_hook(*args, **kwargs):
- print("Post-processing logic here")
- # Modify the result or perform any final logging or cleanup
- return kwargs["result"] # Return the modified or unmodified result
-
- class Preload:
- def __init__(self, connapp):
- # Registering a pre-hook
- connapp.ai.some_method.register_pre_hook(pre_processing_hook)
-
- # Registering a post-hook
- connapp.node.another_method.register_post_hook(post_processing_hook)
- ```
-
-### Executable Block
-- The plugin script can include an executable block:
- - `if __name__ == "__main__":`
- - This block allows the plugin to be run as a standalone script for testing or independent use.
-
-### Script Verification
-- The `verify_script` method in `plugins.py` is used to check the plugin script's compliance with these standards.
-- Non-compliant scripts will be rejected to ensure consistency and proper functionality within the plugin system.
--
-### Example Script
-
-For a practical example of how to write a compatible plugin script, please refer to the following example:
-
-[Example Plugin Script](https://github.com/fluzzi/awspy)
-
-This script demonstrates the required structure and implementation details according to the plugin system's standards.
-
-## http API
-With the Connpy API you can run commands on devices using http requests
-
-### 1. List Nodes
-
-**Endpoint**: `/list_nodes`
-
-**Method**: `POST`
-
-**Description**: This route returns a list of nodes. It can also filter the list based on a given keyword.
-
-#### Request Body:
-
-```json
-{
- "filter": "<keyword>"
-}
-```
-
-* `filter` (optional): A keyword to filter the list of nodes. It returns only the nodes that contain the keyword. If not provided, the route will return the entire list of nodes.
-
-#### Response:
-
-- A JSON array containing the filtered list of nodes.
-
----
-
-### 2. Get Nodes
-
-**Endpoint**: `/get_nodes`
-
-**Method**: `POST`
-
-**Description**: This route returns a dictionary of nodes with all their attributes. It can also filter the nodes based on a given keyword.
-
-#### Request Body:
-
-```json
-{
- "filter": "<keyword>"
-}
-```
-
-* `filter` (optional): A keyword to filter the nodes. It returns only the nodes that contain the keyword. If not provided, the route will return the entire list of nodes.
-
-#### Response:
-
-- A JSON array containing the filtered nodes.
-
----
-
-### 3. Run Commands
-
-**Endpoint**: `/run_commands`
-
-**Method**: `POST`
-
-**Description**: This route runs commands on selected nodes based on the provided action, nodes, and commands. It also supports executing tests by providing expected results.
-
-#### Request Body:
-
-```json
-{
- "action": "<action>",
- "nodes": "<nodes>",
- "commands": "<commands>",
- "expected": "<expected>",
- "options": "<options>"
-}
-```
-
-* `action` (required): The action to be performed. Possible values: `run` or `test`.
-* `nodes` (required): A list of nodes or a single node on which the commands will be executed. The nodes can be specified as individual node names or a node group with the `@` prefix. Node groups can also be specified as arrays with a list of nodes inside the group.
-* `commands` (required): A list of commands to be executed on the specified nodes.
-* `expected` (optional, only used when the action is `test`): A single expected result for the test.
-* `options` (optional): Array to pass options to the run command, options are: `prompt`, `parallel`, `timeout`
-
-#### Response:
-
-- A JSON object with the results of the executed commands on the nodes.
-
----
-
-### 4. Ask AI
-
-**Endpoint**: `/ask_ai`
-
-**Method**: `POST`
-
-**Description**: This route sends to chatgpt IA a request that will parse it into an understandable output for the application and then run the request.
-
-#### Request Body:
-
-```json
-{
- "input": "<user input request>",
- "dryrun": true or false
-}
-```
-
-* `input` (required): The user input requesting the AI to perform an action on some devices or get the devices list.
-* `dryrun` (optional): If set to true, it will return the parameters to run the request but it won't run it. default is false.
-
-#### Response:
-
-- A JSON array containing the action to run and the parameters and the result of the action.
-
-## Automation module
-The automation module
-### Standalone module
-```
-import connpy
-router = connpy.node("uniqueName","ip/host", user="user", password="pass")
-router.run(["term len 0","show run"])
-print(router.output)
-hasip = router.test("show ip int brief","1.1.1.1")
-if hasip:
- print("Router has ip 1.1.1.1")
-else:
- print("router does not have ip 1.1.1.1")
-```
-
-### Using manager configuration
-```
-import connpy
-conf = connpy.configfile()
-device = conf.getitem("server@office")
-server = connpy.node("unique name", **device, config=conf)
-result = server.run(["cd /", "ls -la"])
-print(result)
-```
-### Running parallel tasks
-```
-import connpy
-conf = connpy.configfile()
-#You can get the nodes from the config from a folder and fitlering in it
-nodes = conf.getitem("@office", ["router1", "router2", "router3"])
-#You can also get each node individually:
-nodes = {}
-nodes["router1"] = conf.getitem("router1@office")
-nodes["router2"] = conf.getitem("router2@office")
-nodes["router10"] = conf.getitem("router10@datacenter")
-#Also, you can create the nodes manually:
-nodes = {}
-nodes["router1"] = {"host": "1.1.1.1", "user": "user", "password": "pass1"}
-nodes["router2"] = {"host": "1.1.1.2", "user": "user", "password": "pass2"}
-nodes["router3"] = {"host": "1.1.1.2", "user": "user", "password": "pass3"}
-#Finally you run some tasks on the nodes
-mynodes = connpy.nodes(nodes, config = conf)
-result = mynodes.test(["show ip int br"], "1.1.1.2")
-for i in result:
- print("---" + i + "---")
- print(result[i])
- print()
-# Or for one specific node
-mynodes.router1.run(["term len 0". "show run"], folder = "/home/user/logs")
-```
-### Using variables
-```
-import connpy
-config = connpy.configfile()
-nodes = config.getitem("@office", ["router1", "router2", "router3"])
-commands = []
-commands.append("config t")
-commands.append("interface lo {id}")
-commands.append("ip add {ip} {mask}")
-commands.append("end")
-variables = {}
-variables["router1@office"] = {"ip": "10.57.57.1"}
-variables["router2@office"] = {"ip": "10.57.57.2"}
-variables["router3@office"] = {"ip": "10.57.57.3"}
-variables["__global__"] = {"id": "57"}
-variables["__global__"]["mask"] = "255.255.255.255"
-expected = "!"
-routers = connpy.nodes(nodes, config = config)
-routers.run(commands, variables)
-routers.test("ping {ip}", expected, variables)
-for key in routers.result:
- print(key, ' ---> ', ("pass" if routers.result[key] else "fail"))
-```
-### Using AI
-```
-import connpy
-conf = connpy.configfile()
-organization = 'openai-org'
-api_key = "openai-key"
-myia = connpy.ai(conf, organization, api_key)
-input = "go to router 1 and get me the full configuration"
-result = myia.ask(input, dryrun = False)
-print(result)
-```
-'''
-from .core import node,nodes
-from .configfile import configfile
-from .connapp import connapp
-from .api import *
-from .ai import ai
-from .plugins import Plugins
-from ._version import __version__
-from pkg_resources import get_distribution
-
-__all__ = ["node", "nodes", "configfile", "connapp", "ai", "Plugins"]
-__author__ = "Federico Luzzi"
-__pdoc__ = {
- 'core': False,
- 'completion': False,
- 'api': False,
- 'plugins': False,
- 'core_plugins': False,
- 'hooks': False,
- 'connapp.start': False,
- 'ai.deferred_class_hooks': False,
- 'configfile.deferred_class_hooks': False,
- 'node.deferred_class_hooks': False,
- 'nodes.deferred_class_hooks': False,
- 'connapp': False,
- 'connapp.encrypt': True
-}
Verifies that a given Python script meets specific structural requirements.
-
This function checks a Python script for compliance with predefined structural
-rules. It ensures that the script contains only allowed top-level elements
-(functions, classes, imports, pass statements, and a specific if name block)
-and that it includes mandatory classes with specific attributes and methods.
-
Arguments:
-
- file_path (str): The file path of the Python script to be verified.
-
-
Returns:
-
- str: A message indicating the type of violation if the script doesn't meet
- the requirements, or False if all requirements are met.
-
-
Verifications:
-
- The presence of only allowed top-level elements.
-- The existence of two specific classes: 'Parser' and 'Entrypoint'. and/or specific class: Preload.
-- 'Parser' class must only have an '__init__' method and must assign 'self.parser'
- and 'self.description'.
-- 'Entrypoint' class must have an '__init__' method accepting specific arguments.
-
-
If any of these checks fail, the function returns an error message indicating
-the reason. If the script passes all checks, the function returns False,
-indicating successful verification.
-
Exceptions:
-
- SyntaxError: If the script contains a syntax error, it is caught and
- returned as a part of the error message.
-
Verifies that a given Python script meets specific structural requirements.
+
This function checks a Python script for compliance with predefined structural
+rules. It ensures that the script contains only allowed top-level elements
+(functions, classes, imports, pass statements, and a specific if name block)
+and that it includes mandatory classes with specific attributes and methods.
+
Arguments:
+
- file_path (str): The file path of the Python script to be verified.
+
+
Returns:
+
- str: A message indicating the type of violation if the script doesn't meet
+ the requirements, or False if all requirements are met.
+
+
Verifications:
+
- The presence of only allowed top-level elements.
+- The existence of two specific classes: 'Parser' and 'Entrypoint'. and/or specific class: Preload.
+- 'Parser' class must only have an '__init__' method and must assign 'self.parser'
+ and 'self.description'.
+- 'Entrypoint' class must have an '__init__' method accepting specific arguments.
+
+
If any of these checks fail, the function returns an error message indicating
+the reason. If the script passes all checks, the function returns False,
+indicating successful verification.
+
Exceptions:
+
- SyntaxError: If the script contains a syntax error, it is caught and
+ returned as a part of the error message.
+
This class generates a ai object. Containts all the information and methods to make requests to openAI chatGPT to run actions on the application.
-
Attributes:
-
- model (str): Model of GPT api to use. Default is gpt-4o-mini.
-
-- temp (float): Value between 0 and 1 that control the randomness
- of generated text, with higher values increasing
- creativity. Default is 0.7.
-
-
Parameters:
-
- config (obj): Pass the object created with class configfile with
- key for decryption and extra configuration if you
- are using connection manager.
-
-
Optional Parameters:
-
- org (str): A unique token identifying the user organization
- to interact with the API.
-
-- api_key (str): A unique authentication token required to access
- and interact with the API.
-
-- model (str): Model of GPT api to use. Default is gpt-4o-mini.
-
-- temp (float): Value between 0 and 1 that control the randomness
- of generated text, with higher values increasing
- creativity. Default is 0.7.
-
Expand source code
@@ -1651,52 +1192,38 @@ Categorize the user's request based on the operation they want to perform on
output["result"] = mynodes.run(**output["args"])
return output
+
This class generates a ai object. Containts all the information and methods to make requests to openAI chatGPT to run actions on the application.
+
Attributes:
+
- model (str): Model of GPT api to use. Default is gpt-4o-mini.
+
+- temp (float): Value between 0 and 1 that control the randomness
+ of generated text, with higher values increasing
+ creativity. Default is 0.7.
+
+
Parameters:
+
- config (obj): Pass the object created with class configfile with
+ key for decryption and extra configuration if you
+ are using connection manager.
+
+
Optional Parameters:
+
- org (str): A unique token identifying the user organization
+ to interact with the API.
+
+- api_key (str): A unique authentication token required to access
+ and interact with the API.
+
+- model (str): Model of GPT api to use. Default is gpt-4o-mini.
+
+- temp (float): Value between 0 and 1 that control the randomness
+ of generated text, with higher values increasing
+ creativity. Default is 0.7.
+
Send the user input to openAI GPT and parse the response to run an action in the application.
-
Parameters:
-
- user_input (str): Request to send to openAI that will be parsed
- and returned to execute on the application.
- AI understands the following tasks:
- - Run a command on a group of devices.
- - List a group of devices.
- - Test a command on a group of devices
- and verify if the output contain an
- expected value.
-
-
Optional Parameters:
-
- dryrun (bool): Set to true to get the arguments to use to
- run in the app. Default is false and it
- will run the actions directly.
-- chat_history (list): List in gpt api format for the chat history.
-- max_retries (int): Maximum number of retries for gpt api.
-- backoff_num (int): Backoff factor for exponential wait time
- between retries.
-
-
Returns:
-
dict: Dictionary formed with the following keys:
- - input: User input received
- - app_related: True if GPT detected the request to be related
- to the application.
- - dryrun: True/False
- - response: If the request is not related to the app. this
- key will contain chatGPT answer.
- - action: The action detected by the AI to run in the app.
- - filter: If it was detected by the AI, the filter used
- to get the list of nodes to work on.
- - nodes: If it's not a dryrun, the list of nodes matched by
- the filter.
- - args: A dictionary of arguments required to run command(s)
- on the nodes.
- - result: A dictionary with the output of the commands or
- the test.
- - chat_history: The chat history between user and chatbot.
- It can be used as an attribute for next request.
-
Send the user input to openAI GPT and parse the response to run an action in the application.
+
Parameters:
+
- user_input (str): Request to send to openAI that will be parsed
+ and returned to execute on the application.
+ AI understands the following tasks:
+ - Run a command on a group of devices.
+ - List a group of devices.
+ - Test a command on a group of devices
+ and verify if the output contain an
+ expected value.
+
+
Optional Parameters:
+
- dryrun (bool): Set to true to get the arguments to use to
+ run in the app. Default is false and it
+ will run the actions directly.
+- chat_history (list): List in gpt api format for the chat history.
+- max_retries (int): Maximum number of retries for gpt api.
+- backoff_num (int): Backoff factor for exponential wait time
+ between retries.
+
+
Returns:
+
dict: Dictionary formed with the following keys:
+ - input: User input received
+ - app_related: True if GPT detected the request to be related
+ to the application.
+ - dryrun: True/False
+ - response: If the request is not related to the app. this
+ key will contain chatGPT answer.
+ - action: The action detected by the AI to run in the app.
+ - filter: If it was detected by the AI, the filter used
+ to get the list of nodes to work on.
+ - nodes: If it's not a dryrun, the list of nodes matched by
+ the filter.
+ - args: A dictionary of arguments required to run command(s)
+ on the nodes.
+ - result: A dictionary with the output of the commands or
+ the test.
+ - chat_history: The chat history between user and chatbot.
+ It can be used as an attribute for next request.
+
This class generates a configfile object. Containts a dictionary storing, config, nodes and profiles, normaly used by connection manager.
-
Attributes:
-
- file (str): Path/file to config file.
-
-- key (str): Path/file to RSA key file.
-
-- config (dict): Dictionary containing information of connection
- manager configuration.
-
-- connections (dict): Dictionary containing all the nodes added to
- connection manager.
-
-- profiles (dict): Dictionary containing all the profiles added to
- connection manager.
-
-- privatekey (obj): Object containing the private key to encrypt
- passwords.
-
-- publickey (obj): Object containing the public key to decrypt
- passwords.
-
-
Optional Parameters:
-
- conf (str): Path/file to config file. If left empty default
- path is ~/.config/conn/config.json
-
-- key (str): Path/file to RSA key file. If left empty default
- path is ~/.config/conn/.osk
-
This class generates a configfile object. Containts a dictionary storing, config, nodes and profiles, normaly used by connection manager.
+
Attributes:
+
- file (str): Path/file to config file.
+
+- key (str): Path/file to RSA key file.
+
+- config (dict): Dictionary containing information of connection
+ manager configuration.
+
+- connections (dict): Dictionary containing all the nodes added to
+ connection manager.
+
+- profiles (dict): Dictionary containing all the profiles added to
+ connection manager.
+
+- privatekey (obj): Object containing the private key to encrypt
+ passwords.
+
+- publickey (obj): Object containing the public key to decrypt
+ passwords.
+
+
Optional Parameters:
+
- conf (str): Path/file to config file. If left empty default
+ path is ~/.config/conn/config.json
+
+- key (str): Path/file to RSA key file. If left empty default
+ path is ~/.config/conn/.osk
+
Methods
def encrypt(self, password, keyfile=None)
-
Encrypts password using RSA keyfile
-
Parameters:
-
- password (str): Plaintext password to encrypt.
-
-
Optional Parameters:
-
- keyfile (str): Path/file to keyfile. Default is config keyfile.
-
This class generates a node object. Containts all the information and methods to connect and interact with a device using ssh or telnet.
-
Attributes:
-
- output (str): Output of the commands you ran with run or test
- method.
-
-- result(bool): True if expected value is found after running
- the commands using test method.
-
-- status (int): 0 if the method run or test run succesfully.
- 1 if connection failed.
- 2 if expect timeouts without prompt or EOF.
-
-
Parameters:
-
- unique (str): Unique name to assign to the node.
-
-- host (str): IP address or hostname of the node.
-
-
Optional Parameters:
-
- options (str): Additional options to pass the ssh/telnet for
- connection.
-
-- logs (str): Path/file for storing the logs. You can use
- ${unique},${host}, ${port}, ${user}, ${protocol}
- as variables.
-
-- password (str): Encrypted or plaintext password.
-
-- port (str): Port to connect to node, default 22 for ssh and 23
- for telnet.
-
-- protocol (str): Select ssh, telnet, kubectl or docker. Default is ssh.
-
-- user (str): Username to of the node.
-
-- config (obj): Pass the object created with class configfile with
- key for decryption and extra configuration if you
- are using connection manager.
-
-- tags (dict) : Tags useful for automation and personal porpuse
- like "os", "prompt" and "screenleght_command"
-
-- jumphost (str): Reference another node to be used as a jumphost
-
Expand source code
@@ -3136,7 +2660,7 @@ class node:
if results in initial_indices[self.protocol]:
if self.protocol in ["ssh", "sftp"]:
child.sendline('yes')
- elif self.protocol in ["telnet", "kubectl"]:
+ elif self.protocol in ["telnet", "kubectl", "docker"]:
if self.user:
child.sendline(self.user)
else:
@@ -3179,17 +2703,55 @@ class node:
self.child = child
return True
+
This class generates a node object. Containts all the information and methods to connect and interact with a device using ssh or telnet.
+
Attributes:
+
- output (str): Output of the commands you ran with run or test
+ method.
+
+- result(bool): True if expected value is found after running
+ the commands using test method.
+
+- status (int): 0 if the method run or test run succesfully.
+ 1 if connection failed.
+ 2 if expect timeouts without prompt or EOF.
+
+
Parameters:
+
- unique (str): Unique name to assign to the node.
+
+- host (str): IP address or hostname of the node.
+
+
Optional Parameters:
+
- options (str): Additional options to pass the ssh/telnet for
+ connection.
+
+- logs (str): Path/file for storing the logs. You can use
+ ${unique},${host}, ${port}, ${user}, ${protocol}
+ as variables.
+
+- password (str): Encrypted or plaintext password.
+
+- port (str): Port to connect to node, default 22 for ssh and 23
+ for telnet.
+
+- protocol (str): Select ssh, telnet, kubectl or docker. Default is ssh.
+
+- user (str): Username to of the node.
+
+- config (obj): Pass the object created with class configfile with
+ key for decryption and extra configuration if you
+ are using connection manager.
+
+- tags (dict) : Tags useful for automation and personal porpuse
+ like "os", "prompt" and "screenleght_command"
+
+- jumphost (str): Reference another node to be used as a jumphost
+
Methods
def interact(self, debug=False)
-
Allow user to interact with the node directly, mostly used by connection manager.
-
Optional Parameters:
-
- debug (bool): If True, display all the connecting information
- before interact. Default False.
-
Run a command or list of commands on the node and return the output.
-
Parameters:
-
- commands (str/list): Commands to run on the node. Should be
- str or a list of str. You can use variables
- as {varname} and defining them in optional
- parameter vars.
-
-
Optional Parameters:
-
- vars (dict): Dictionary containing the definition of variables
- used in commands parameter.
- Keys: Variable names.
- Values: strings.
-
-
Optional Named Parameters:
-
- folder (str): Path where output log should be stored, leave
- empty to disable logging.
-
-- prompt (str): Prompt to be expected after a command is finished
- running. Usually linux uses ">" or EOF while
- routers use ">" or "#". The default value should
- work for most nodes. Change it if your connection
- need some special symbol.
-
-- stdout (bool):Set True to send the command output to stdout.
- default False.
-
-- timeout (int):Time in seconds for expect to wait for prompt/EOF.
- default 10.
-
-
Returns:
-
str: Output of the commands you ran on the node.
-
Run a command or list of commands on the node, then check if expected value appears on the output after the last command.
+
Run a command or list of commands on the node and return the output.
Parameters:
-
- commands (str/list): Commands to run on the node. Should be
+
- commands (str/list): Commands to run on the node. Should be
str or a list of str. You can use variables
as {varname} and defining them in optional
parameter vars.
-
-- expected (str) : Expected text to appear after running
- all the commands on the node.You can use
- variables as {varname} and defining them
- in optional parameter vars.
Optional Parameters:
- vars (dict): Dictionary containing the definition of variables
- used in commands and expected parameters.
+ used in commands parameter.
Keys: Variable names.
Values: strings.
Optional Named Parameters:
-
- prompt (str): Prompt to be expected after a command is finished
+
- folder (str): Path where output log should be stored, leave
+ empty to disable logging.
+
+- prompt (str): Prompt to be expected after a command is finished
running. Usually linux uses ">" or EOF while
routers use ">" or "#". The default value should
work for most nodes. Change it if your connection
need some special symbol.
+- stdout (bool):Set True to send the command output to stdout.
+ default False.
+
- timeout (int):Time in seconds for expect to wait for prompt/EOF.
default 10.
Returns:
-
bool: true if expected value is found after running the commands
- false if prompt is found before.
+
Run a command or list of commands on the node, then check if expected value appears on the output after the last command.
+
Parameters:
+
- commands (str/list): Commands to run on the node. Should be
+ str or a list of str. You can use variables
+ as {varname} and defining them in optional
+ parameter vars.
+
+- expected (str) : Expected text to appear after running
+ all the commands on the node.You can use
+ variables as {varname} and defining them
+ in optional parameter vars.
+
+
Optional Parameters:
+
- vars (dict): Dictionary containing the definition of variables
+ used in commands and expected parameters.
+ Keys: Variable names.
+ Values: strings.
+
+
Optional Named Parameters:
+
- prompt (str): Prompt to be expected after a command is finished
+ running. Usually linux uses ">" or EOF while
+ routers use ">" or "#". The default value should
+ work for most nodes. Change it if your connection
+ need some special symbol.
+
+- timeout (int):Time in seconds for expect to wait for prompt/EOF.
+ default 10.
+
+
Returns:
+
bool: true if expected value is found after running the commands
+ false if prompt is found before.
+
This class generates a nodes object. Contains a list of node class objects and methods to run multiple tasks on nodes simultaneously.
-
Attributes:
-
- nodelist (list): List of node class objects passed to the init
- function.
-
-- output (dict): Dictionary formed by nodes unique as keys,
- output of the commands you ran on the node as
- value. Created after running methods run or test.
-
-- result (dict): Dictionary formed by nodes unique as keys, value
- is True if expected value is found after running
- the commands, False if prompt is found before.
- Created after running method test.
-
-- status (dict): Dictionary formed by nodes unique as keys, value:
- 0 if method run or test ended succesfully.
- 1 if connection failed.
- 2 if expect timeouts without prompt or EOF.
-
-- <unique> (obj): For each item in nodelist, there is an attribute
- generated with the node unique.
-
-
Parameters:
-
- nodes (dict): Dictionary formed by node information:
- Keys: Unique name for each node.
- Mandatory Subkeys: host(str).
- Optional Subkeys: options(str), logs(str), password(str),
- port(str), protocol(str), user(str).
- For reference on subkeys check node class.
-
-
Optional Parameters:
-
- config (obj): Pass the object created with class configfile with key
- for decryption and extra configuration if you are using
- connection manager.
-
Expand source code
@@ -3792,51 +3324,47 @@ class nodes:
self.status = status
return result
+
This class generates a nodes object. Contains a list of node class objects and methods to run multiple tasks on nodes simultaneously.
+
Attributes:
+
- nodelist (list): List of node class objects passed to the init
+ function.
+
+- output (dict): Dictionary formed by nodes unique as keys,
+ output of the commands you ran on the node as
+ value. Created after running methods run or test.
+
+- result (dict): Dictionary formed by nodes unique as keys, value
+ is True if expected value is found after running
+ the commands, False if prompt is found before.
+ Created after running method test.
+
+- status (dict): Dictionary formed by nodes unique as keys, value:
+ 0 if method run or test ended succesfully.
+ 1 if connection failed.
+ 2 if expect timeouts without prompt or EOF.
+
+- <unique> (obj): For each item in nodelist, there is an attribute
+ generated with the node unique.
+
+
Parameters:
+
- nodes (dict): Dictionary formed by node information:
+ Keys: Unique name for each node.
+ Mandatory Subkeys: host(str).
+ Optional Subkeys: options(str), logs(str), password(str),
+ port(str), protocol(str), user(str).
+ For reference on subkeys check node class.
+
+
Optional Parameters:
+
- config (obj): Pass the object created with class configfile with key
+ for decryption and extra configuration if you are using
+ connection manager.
+
Run a command or list of commands on all the nodes in nodelist.
-
Parameters:
-
- commands (str/list): Commands to run on the nodes. Should be str or
- list of str. You can use variables as {varname}
- and defining them in optional parameter vars.
-
-
Optional Parameters:
-
- vars (dict): Dictionary containing the definition of variables for
- each node, used in commands parameter.
- Keys should be formed by nodes unique names. Use
- special key name __global__ for global variables.
- Subkeys: Variable names.
- Values: strings.
-
-
Optional Named Parameters:
-
- folder (str): Path where output log should be stored, leave empty
- to disable logging.
-
-- prompt (str): Prompt to be expected after a command is finished
- running. Usually linux uses ">" or EOF while routers
- use ">" or "#". The default value should work for
- most nodes. Change it if your connection need some
- special symbol.
-
-- stdout (bool): Set True to send the command output to stdout.
- Default False.
-
-- parallel (int): Number of nodes to run the commands simultaneously.
- Default is 10, if there are more nodes that this
- value, nodes are groups in groups with max this
- number of members.
-
-- timeout (int): Time in seconds for expect to wait for prompt/EOF.
- default 10.
-
-
Returns:
-
dict: Dictionary formed by nodes unique as keys, Output of the
- commands you ran on the node as value.
-
Expand source code
@@ -3926,34 +3454,32 @@ def run(self, commands, vars = None,*, folder = None, prompt = None, stdout = No
self.status = status
return output
-
Run a command or list of commands on all the nodes in nodelist, then check if expected value appears on the output after the last command.
+
Run a command or list of commands on all the nodes in nodelist.
Parameters:
-
- commands (str/list): Commands to run on the node. Should be str or
- list of str.
-
-- expected (str) : Expected text to appear after running all the
- commands on the node.
+
- commands (str/list): Commands to run on the nodes. Should be str or
+ list of str. You can use variables as {varname}
+ and defining them in optional parameter vars.
Optional Parameters:
- vars (dict): Dictionary containing the definition of variables for
- each node, used in commands and expected parameters.
+ each node, used in commands parameter.
Keys should be formed by nodes unique names. Use
special key name __global__ for global variables.
Subkeys: Variable names.
Values: strings.
Optional Named Parameters:
-
- prompt (str): Prompt to be expected after a command is finished
- running. Usually linux uses ">" or EOF while
- routers use ">" or "#". The default value should
- work for most nodes. Change it if your connection
- need some special symbol.
+
- folder (str): Path where output log should be stored, leave empty
+ to disable logging.
+- prompt (str): Prompt to be expected after a command is finished
+ running. Usually linux uses ">" or EOF while routers
+ use ">" or "#". The default value should work for
+ most nodes. Change it if your connection need some
+ special symbol.
+
+- stdout (bool): Set True to send the command output to stdout.
+ Default False.
- parallel (int): Number of nodes to run the commands simultaneously.
Default is 10, if there are more nodes that this
@@ -3964,10 +3490,14 @@ def run(self, commands, vars = None,*, folder = None, prompt = None, stdout = No
default 10.
Returns:
-
dict: Dictionary formed by nodes unique as keys, value is True if
- expected value is found after running the commands, False
- if prompt is found before.
+
dict: Dictionary formed by nodes unique as keys, Output of the
+ commands you ran on the node as value.
Expand source code
@@ -4054,6 +3584,43 @@ def test(self, commands, expected, vars = None,*, prompt = None, parallel = 10,
self.status = status
return result
+
Run a command or list of commands on all the nodes in nodelist, then check if expected value appears on the output after the last command.
+
Parameters:
+
- commands (str/list): Commands to run on the node. Should be str or
+ list of str.
+
+- expected (str) : Expected text to appear after running all the
+ commands on the node.
+
+
Optional Parameters:
+
- vars (dict): Dictionary containing the definition of variables for
+ each node, used in commands and expected parameters.
+ Keys should be formed by nodes unique names. Use
+ special key name __global__ for global variables.
+ Subkeys: Variable names.
+ Values: strings.
+
+
Optional Named Parameters:
+
- prompt (str): Prompt to be expected after a command is finished
+ running. Usually linux uses ">" or EOF while
+ routers use ">" or "#". The default value should
+ work for most nodes. Change it if your connection
+ need some special symbol.
+
+
+- parallel (int): Number of nodes to run the commands simultaneously.
+ Default is 10, if there are more nodes that this
+ value, nodes are groups in groups with max this
+ number of members.
+
+- timeout (int): Time in seconds for expect to wait for prompt/EOF.
+ default 10.
+
+
Returns:
+
dict: Dictionary formed by nodes unique as keys, value is True if
+ expected value is found after running the commands, False
+ if prompt is found before.
+