### Install Local Net-SNMPd
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/benchmarks/preparing.md
Execute the setup script to install Net-SNMPd locally. This is a prerequisite for certain benchmark operations.
```bash
./tools/build/setup-snmpd.sh
```
--------------------------------
### Fetch Example Script
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/examples/async/fetch.md
This is the main script for the fetch example, demonstrating the use of Gufo SNMP's fetch functionality.
```python
--8<-- "examples/async/fetch.py"
```
--------------------------------
### Async Get Request Example
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/examples/async/get.md
This snippet shows the complete asynchronous Python code for performing a single SNMP GET request. It includes necessary imports, session setup, and the actual GET operation.
```python
import asyncio
import sys
from gufo.snmp.async_client import SnmpSession
async def main(address: str, community: str, oid: str):
print("Gufo SNMP Test")
async with SnmpSession(address, community) as session:
response = await session.get(oid)
print(response)
if __name__ == "__main__":
address = sys.argv[1]
community = sys.argv[2]
oid = sys.argv[3]
asyncio.run(main(address, community, oid))
```
--------------------------------
### Full SNMPv3 Get Request Example
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/examples/async/get-v3.md
This is the complete Python script for performing an SNMPv3 Get request. It includes setup for authentication, privacy, and the asynchronous execution of the request.
```python
import asyncio
import sys
from gufo.snmp import SnmpSession, User
from gufo.snmp.auth import NoAuth, MD5, SHA
from gufo.snmp.priv import NoPriv, DES, AES128
AUTH_ALG = {
"no_auth": NoAuth,
"md5": MD5,
"sha": SHA,
}
PRIV_ALG = {
"no_priv": NoPriv,
"des": DES,
"aes128": AES128,
}
def get_user() -> User:
"""Get user from CLI arguments."""
username = sys.argv[1]
auth_alg_name = sys.argv[2]
auth_key = sys.argv[3].encode() if len(sys.argv) > 3 else None
priv_alg_name = sys.argv[4] if len(sys.argv) > 4 else "no_priv"
priv_key = sys.argv[5].encode() if len(sys.argv) > 5 else None
auth_alg = AUTH_ALG.get(auth_alg_name)
priv_alg = PRIV_ALG.get(priv_alg_name)
return User(
username=username,
auth_alg=auth_alg,
auth_key=auth_key,
priv_alg=priv_alg,
priv_key=priv_key,
)
async def main():
"""Run main logic."""
user = get_user()
session = SnmpSession(user=user)
# Example: Get system description (OID: 1.3.6.1.2.1.1.1.0)
oid = "1.3.6.1.2.1.1.1.0"
response = await session.get(sys.argv[6], oid)
print(f"Received response: {response}")
if __name__ == "__main__":
asyncio.run(main())
```
--------------------------------
### Execute the asynchronous main function
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/examples/async/get-v3.md
Uses `asyncio.run()` to execute the `main` asynchronous function, starting the SNMPv3 Get request process from a synchronous context.
```python
if __name__ == "__main__":
asyncio.run(main())
```
--------------------------------
### Install Python Dependencies
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/benchmarks/preparing.md
Install the gufo-snmp package with test and benchmark extras. This command installs the package in editable mode and includes all necessary dependencies for testing and benchmarking.
```bash
pip install -e gufo-snmp[test,bench]
```
--------------------------------
### Full getmany example
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/examples/sync/getmany.md
A complete synchronous example demonstrating how to query multiple SNMP OIDs using `get_many()`. It includes argument parsing, session initialization, the request, and result processing.
```Python
import sys
from typing import List
from gufo.snmp.sync_client import SnmpSession
def main(address: str, community: str, oids: List[str]):
with SnmpSession(address=address, community=community) as session:
results = session.get_many(oids=oids)
for oid, value in results.items():
print(f"{oid}: {value}")
if __name__ == "__main__":
if len(sys.argv) < 4:
print("Usage: python getmany.py
[oid2] ...")
sys.exit(1)
agent_address = sys.argv[1]
snmp_community = sys.argv[2]
query_oids = sys.argv[3:]
main(agent_address, snmp_community, query_oids)
```
--------------------------------
### GetNext Request Example (Python)
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/examples/async/getnext.md
This is the main example script for performing an asynchronous GetNext request. It imports necessary modules and defines the main asynchronous function.
```python
--8<-- "examples/async/getnext.py"
```
--------------------------------
### Define and Run Main Function
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/examples/sync/debugging.md
Define the main function for the debugging example and execute it.
```python
def main():
base_oid = OID("1.3.6.1.2.1.1")
with Snmpd() as snmpd:
with SnmpSession(snmpd.address) as session:
for oid, value in session.getnext(base_oid):
print(f"{oid}: {value}")
if __name__ == "__main__":
main()
```
--------------------------------
### Install Editable Package
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/dev/testing.md
Installs the package in editable mode, useful for rebuilding rust modules when they have changed.
```shell
python -m pip install --editable .
```
--------------------------------
### Synchronous SNMP Rate Limiting Example
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/examples/sync/ratelimit.md
This is the main example demonstrating synchronous SNMP rate limiting. It sets up an SNMP session with a specified requests per second limit and fetches MIB data.
```python
--8<-- "examples/sync/ratelimit.py"
```
--------------------------------
### Check Gufo SNMP Installation
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/installation.md
Import the __version__ attribute from the gufo.snmp module to verify that the installation was successful.
```python
from gufo.snmp import __version__
```
--------------------------------
### Install Gufo SNMP
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/installation.md
Use this command to install the Gufo SNMP package using pip.
```bash
pip install gufo_snmp
```
--------------------------------
### Install System Packages for Debian/Ubuntu
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/benchmarks/preparing.md
Install the libsnmp-dev package on Debian or Ubuntu systems. This package provides necessary development headers for Net-SNMP.
```bash
sudo apt-get install libsnmp-dev
```
--------------------------------
### Run the asynchronous main function
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/examples/async/debugging.md
Execute the main asynchronous function using asyncio.run() to start the application.
```python
asyncio.run(main())
```
--------------------------------
### Install System Packages for RHEL/CentOS
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/benchmarks/preparing.md
Install the net-snmp-devel package on RHEL or CentOS systems. This package provides necessary development headers for Net-SNMP.
```bash
sudo yum install net-snmp-devel
```
--------------------------------
### Fetch MIB Data with Gufo SNMP
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/examples/sync/fetch.md
This snippet demonstrates the basic structure of the fetch example script, including importing the sys module for command-line arguments.
```python
--8<-- "examples/sync/fetch.py"
```
--------------------------------
### Define asynchronous main function for SNMPv3 Get
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/examples/async/get-v3.md
Defines an asynchronous function `main` that takes the agent address, User instance, and OID as arguments. It initializes an `SnmpSession` and performs the GET request.
```python
async def main():
"""Run main logic."""
user = get_user()
session = SnmpSession(user=user)
# Example: Get system description (OID: 1.3.6.1.2.1.1.1.0)
oid = "1.3.6.1.2.1.1.1.0"
response = await session.get(sys.argv[6], oid)
print(f"Received response: {response}")
```
--------------------------------
### Synchronous SNMP Get Request Example
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/examples/sync/get.md
This snippet demonstrates a basic synchronous SNMP GET request to retrieve a single OID value. It requires the agent address, community string, and the target OID as input.
```python
import sys
from gufo.snmp.sync_client import SnmpSession
def main():
# Arguments: agent address, community, OID
if len(sys.argv) != 4:
print("Usage: python3 get.py ")
sys.exit(1)
agent_address = sys.argv[1]
community = sys.argv[2]
oid = sys.argv[3]
# Create an SNMP session
# The SnmpSession can be used directly or as a context manager
# Using it as a context manager ensures the session is closed automatically
with SnmpSession(agent_address=agent_address, community=community) as session:
# Perform the GET request for the specified OID
response = session.get(oid=oid)
# Print the result
print(f"OID: {oid}")
print(f"Value: {response.value}")
if __name__ == "__main__":
main()
```
--------------------------------
### Python SNMPv3 Get Request Example
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/examples/sync/get-v3.md
This snippet shows the complete Python code for performing an SNMPv3 Get request using Gufo SNMP. It includes all necessary imports and function definitions.
```python
--8<-- "examples/sync/get-v3.py"
```
--------------------------------
### Python GetBulk Request Example
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/examples/async/getbulk.md
This is the main Python script for performing an asynchronous SNMP GetBulk request. It includes all necessary imports and logic for the example.
```python
--8<-- "examples/async/getbulk.py"
```
--------------------------------
### Command-Line Utility GET Request
Source: https://github.com/gufolabs/gufo_snmp/blob/master/README.md
Use the `gufo-snmp` command-line utility to perform SNMP GET requests. It mimics the functionality of Net-SNMP tools.
```shell
gufo-snmp -v2c -c public 127.0.0.1 1.3.6.1.2.1.1.6.0
1.3.6.1.2.1.1.6.0 = Gufo SNMP Test
```
--------------------------------
### Async SNMPv3 GET Request
Source: https://github.com/gufolabs/gufo_snmp/blob/master/README.md
Perform a GET request using SNMPv3 authentication and privacy. Requires defining user credentials, authentication keys, and privacy keys.
```python
from gufo.snmp import SnmpSession, User, Sha1Key, Aes128Key
async with SnmpSession(
addr="127.0.0.1",
user=User(
"user1",
auth_key=Sha1Key(b"12345678"),
priv_key=Aes128Key(b"87654321")
)
) as session:
r = await session.get("1.3.6.1.2.1.1.3.0")
```
--------------------------------
### Define main function with expected arguments
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/examples/sync/get-v3.md
Defines the main function, specifying its expected arguments: agent address, User instance, and the OID to query. This sets up the core logic for the SNMP Get request.
```python
--8<-- "examples/sync/get-v3.py:32:35"
```
--------------------------------
### Async GET Request
Source: https://github.com/gufolabs/gufo_snmp/blob/master/README.md
Query a single MIB key using the asynchronous session. Ensure the SnmpSession is properly awaited.
```python
from gufo.snmp import SnmpSession
async with SnmpSession(addr="127.0.0.1", community="public") as session:
r = await session.get("1.3.6.1.2.1.1.3.0")
```
--------------------------------
### Run the main asynchronous function
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/examples/async/ratelimit.md
Execute the `main` asynchronous function using `asyncio.run()`, passing command-line arguments for the agent address, community, and OID. This starts the SNMP polling process.
```python
if __name__ == '__main__':
asyncio.run(main(sys.argv[1], sys.argv[2], sys.argv[3]))
```
--------------------------------
### GetNext Request Example
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/examples/sync/getnext.md
This snippet demonstrates how to perform an SNMP GetNext request to iterate through all keys under a given OID. It requires importing the sys module for command-line arguments and the SnmpSession from gufo.snmp.sync_client.
```python
import sys
from gufo.snmp.sync_client import SnmpSession
def main():
if len(sys.argv) != 4:
print('Usage: python3 getnext.py ')
sys.exit(1)
agent_address = sys.argv[1]
community = sys.argv[2]
base_oid = sys.argv[3]
# Create SnmpSession object
with SnmpSession(agent_address=agent_address, community=community) as session:
# Iterate over values using getnext()
for oid, value in session.getnext(base_oid):
print(f'{oid}: {value}')
if __name__ == '__main__':
main()
```
--------------------------------
### Async Get Multiple MIB Keys
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/index.md
Query multiple MIB keys in a single request using the asynchronous session.
```python
async with SnmpSession(addr="127.0.0.1", community="public") as session:
r = await session.get_many(["1.3.6.1.2.1.1.3.0", "1.3.6.1.2.1.1.2.0"])
```
--------------------------------
### Perform SNMP GET Request
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/examples/async/get-v3.md
This snippet demonstrates how to use the `get()` method of an `SnmpSession` to asynchronously retrieve a value for a given OID. The result must be awaited.
```python
response = await session.get(oid)
```
--------------------------------
### Run SNMP v3 GETBULK Benchmarks
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/benchmarks/v3/getbulk.md
Execute the benchmark tests for SNMP v3 GETBULK requests using pytest. Ensure you have the necessary dependencies installed.
```bash
pytest benchmarks/test_v3_getbulk.py
```
--------------------------------
### Async Multi-Item Get Request with Gufo SNMP
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/examples/async/getmany.md
This snippet shows the complete asynchronous function to perform a multi-item GET request. It initializes an SNMP session and queries a list of OIDs.
```python
import asyncio
import sys
from typing import List
from gufo.snmp.async_client import SnmpSession
async def main(address: str, community: str, oids: List[str]):
async with SnmpSession(address=address, community=community) as session:
result = await session.get_many(oids)
for oid, value in result.items():
print(f"{oid}: {value}")
if __name__ == "__main__":
asyncio.run(main(sys.argv[1], sys.argv[2], sys.argv[3:]))
```
--------------------------------
### Print SNMP GET Response
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/examples/async/get-v3.md
This snippet shows how to print the received response from an SNMP GET request. The application is responsible for processing the response data.
```python
print(response)
```
--------------------------------
### Perform SNMPv3 GET request
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/examples/async/get-v3.md
Executes an asynchronous GET request using the `SnmpSession`. It targets the specified agent address (from CLI arguments) and OID, retrieving a single management information base (MIB) object.
```python
response = await session.get(sys.argv[6], oid)
```
--------------------------------
### Run SNMP v2c GETNEXT Benchmarks
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/benchmarks/v2c/getnext.md
Execute the benchmark tests for SNMP v2c GETNEXT requests using pytest. Ensure you have the necessary dependencies installed.
```bash
pytest benchmarks/test_v2c_getnext.py
```
--------------------------------
### Run SNMP v2c GETBULK Benchmark Tests
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/benchmarks/v2c/getbulk.md
Execute the benchmark tests for SNMP v2c GETBULK requests using pytest. Ensure you have the necessary dependencies installed.
```bash
pytest benchmarks/test_v2c_getbulk.py
```
--------------------------------
### Print retrieved SNMP data
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/examples/async/debugging.md
Process the results obtained from SNMP queries as needed. This example simply prints each OID and its corresponding value.
```python
print(f'{oid}: {value}')
```
--------------------------------
### Iterate using SnmpSession.getnext()
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/examples/async/debugging.md
Use the asynchronous iterator SnmpSession.getnext() with an async for loop to retrieve OID-value pairs, starting from a base OID.
```python
async for oid, value in session.getnext(oid='1.3.6.1.2.1.1'):
```
--------------------------------
### Async GET Many Request
Source: https://github.com/gufolabs/gufo_snmp/blob/master/README.md
Query multiple MIB keys in a single request using the asynchronous session. This is more efficient for retrieving several values at once.
```python
async with SnmpSession(addr="127.0.0.1", community="public") as session:
r = await session.get_many(["1.3.6.1.2.1.1.3.0", "1.3.6.1.2.1.1.2.0"])
```
--------------------------------
### Iterate with SnmpSession.getnext()
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/examples/sync/debugging.md
Use `SnmpSession.getnext()` to iterate over values starting from a base OID. The function yields pairs of (OID, value).
```python
for oid, value in session.getnext(base_oid):
print(f"{oid}: {value}")
```
--------------------------------
### Upgrade Gufo SNMP
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/installation.md
Use this command to upgrade an existing Gufo SNMP installation to the latest version using pip.
```bash
pip install --upgrade gufo_snmp
```
--------------------------------
### Async GETNEXT Request
Source: https://github.com/gufolabs/gufo_snmp/blob/master/README.md
Iterate through MIB entries starting from a specified OID using the GETNEXT request. This is useful for traversing MIB tables.
```python
async with SnmpSession(addr="127.0.0.1", community="public") as session:
async for oid, value in session.getnext("1.3.6.1.2.1.1"):
...
```
--------------------------------
### Synchronous GET Request
Source: https://github.com/gufolabs/gufo_snmp/blob/master/README.md
Query a single MIB key using the synchronous session. This mode shares the API with the async version but uses standard Python context managers.
```python
from gufo.snmp.sync_client import SnmpSession
with SnmpSession(addr="127.0.0.1", community="public") as session:
r = session.get("1.3.6.1.2.1.1.3.0")
```
--------------------------------
### Get User instance with authentication and privacy settings
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/examples/sync/get-v3.md
Defines the 'get_user' function to process command-line arguments and construct a Gufo SNMP 'User' object. This function handles username, authentication, and privacy configurations.
```python
--8<-- "examples/sync/get-v3.py:17:29"
```
--------------------------------
### Fetch data using SnmpSession.fetch
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/examples/async/ratelimit.md
Use the `SnmpSession.fetch()` method within an `async for` loop to iterate over OID-value pairs starting from a base OID. This method is an asynchronous iterator.
```python
async for oid, value in session.fetch(oid=oid):
pass
```
--------------------------------
### Function to get SNMPv3 User from CLI arguments
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/examples/async/get-v3.md
Parses command-line arguments to construct a `User` object for SNMPv3. It extracts username, authentication algorithm and key, and privacy algorithm and key, handling optional parameters.
```python
def get_user() -> User:
"""Get user from CLI arguments."""
username = sys.argv[1]
auth_alg_name = sys.argv[2]
auth_key = sys.argv[3].encode() if len(sys.argv) > 3 else None
priv_alg_name = sys.argv[4] if len(sys.argv) > 4 else "no_priv"
priv_key = sys.argv[5].encode() if len(sys.argv) > 5 else None
auth_alg = AUTH_ALG.get(auth_alg_name)
priv_alg = PRIV_ALG.get(priv_alg_name)
return User(
username=username,
auth_alg=auth_alg,
auth_key=auth_key,
priv_alg=priv_alg,
priv_key=priv_key,
)
```
--------------------------------
### Configure and Run Benchmarks
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/dev/testing.md
Configures the project for benchmarking by modifying Cargo.toml, then runs the benchmarks using cargo bench. Remember to revert the changes to Cargo.toml after completion.
```toml
crate-type = ["cdylib"] # Comment for bench
```
```toml
# crate-type = ["cdylib", "rlib"] # Uncomment for bench
```
--------------------------------
### Serve Documentation Locally
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/dev/testing.md
Rebuilds and serves the project documentation locally for review. It is recommended to use Grammarly for checking documentation for common errors.
```shell
mkdocs serve
```
--------------------------------
### Build Package
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/dev/testing.md
Builds the package into source distribution and wheel formats. Compiled packages will be available in the dist/ directory.
```shell
python -m build --sdist --wheel
```
--------------------------------
### Run Benchmarks
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/dev/testing.md
Executes the project's benchmarks using cargo bench. This command should be run after configuring Cargo.toml for benchmarking.
```shell
cargo bench
```
--------------------------------
### Run Asynchronous Main Function
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/examples/async/get-v3.md
This snippet shows how to execute the main asynchronous function using `asyncio.run()`. It passes command-line arguments for the agent address, user credentials, and OID.
```python
asyncio.run(main(sys.argv[1], get_user(sys.argv[2], sys.argv[3], sys.argv[4]), sys.argv[5]))
```
--------------------------------
### Create Snmpd and SnmpSession context
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/examples/async/debugging.md
Use an async with clause to manage both the Snmpd context for the local snmpd instance and the SnmpSession object for the client's session. Both are asynchronous context managers.
```python
async with Snmpd() as snmpd, SnmpSession() as session:
```
--------------------------------
### Run the asynchronous main function
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/examples/async/engine-id-discovery.md
Execute the asynchronous main() function using asyncio.run(), passing the agent address and username obtained from command-line arguments.
```python
asyncio.run(main(sys.argv[1], sys.argv[2]))
```
--------------------------------
### Initialize SnmpSession with User object
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/examples/async/get-v3.md
Creates an instance of `SnmpSession`, passing the configured `User` object. This session will be used to perform SNMP operations with the specified v3 security credentials.
```python
session = SnmpSession(user=user)
```
--------------------------------
### Import Gufo SNMP core components
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/examples/async/get-v3.md
Import necessary classes and algorithms from `gufo.snmp` for creating SNMP sessions and defining user-based security model (USM) configurations, including authentication and privacy helpers.
```python
from gufo.snmp import SnmpSession, User
from gufo.snmp.auth import NoAuth, MD5, SHA
from gufo.snmp.priv import NoPriv, DES, AES128
```
--------------------------------
### Initialize SnmpSession and Snmpd Context
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/examples/sync/debugging.md
Initialize `Snmpd` context for a local snmpd instance and create a `SnmpSession` object using context managers.
```python
with Snmpd() as snmpd:
with SnmpSession(snmpd.address) as session:
```
--------------------------------
### Async SNMPd Daemon Wrapper
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/index.md
Run a local instance of an SNMP daemon using the Snmpd wrapper and connect to it with an asynchronous session.
```python
async with Snmpd(), SnmpSession(addr="127.0.0.1", port=10161) as session:
r = await session.get("1.3.6.1.2.1.1.3.0")
```
--------------------------------
### Perform SNMP GET Request
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/examples/sync/get-v3.md
Use the SnmpSession.get() method to query a specific OID. This is the core function for retrieving a single SNMP object value.
```python
response = session.get(oid)
```
--------------------------------
### gufo-snmp Usage
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/man/gufo-snmp.md
Displays the command-line usage instructions for gufo-snmp, outlining available arguments and options for SNMP requests.
```bash
usage: gufo-snmp [-h] [--version {v1,v2c,v3}] [-v1 | -v2c | -v3] [--command {GET,GETNEXT,GETBULK}] [-p PORT]
[-c COMMUNITY] [-u USER] [-a {MD5,SHA}] [-A AUTH_PASS] [-x {DES,AES}] [-X SECURITY_PASS] [-O OFLAGS]
address ...
SNMP Client
positional arguments:
address Agent
oids OIDs
options:
-h, --help show this help message and exit
--version {v1,v2c,v3}
SNMP Protocol version
-v1 SNMP v1
-v2c SNMP v2c
-v3 SNMP v3
--command {GET,GETNEXT,GETBULK}
Command
-p, --port PORT Argent port
-c, --community COMMUNITY
Community (v1/v2c)
-u, --user USER User name (v3)
-a, --auth-protocol {MD5,SHA}
Set authentication protocol (v3)
-A, --auth-pass AUTH_PASS
Set authentication protocol pass-phrase (v3)
-x, --security-protocol {DES,AES}
Set security protocol (v3)
-X, --security-pass SECURITY_PASS
Set security protocol pass-phrase (v3)
-O OFLAGS Output formatting flags (may be repeated or combined)
Supported flags:
a : print all strings in ascii format
x : print all strings in hex format
q : quick print for easier parsing
Q : quick print with equal-signs
T : print human-readable text along with hex strings
v : print values only (not OID = value)
```
--------------------------------
### Initialize SnmpSession
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/examples/sync/getmany.md
Initialize an `SnmpSession` object with the agent's address and SNMP community. The session can be used directly or as a context manager.
```Python
from gufo.snmp.sync_client import SnmpSession
def main(address: str, community: str, oids: List[str]):
# ...
with SnmpSession(address=address, community=community) as session:
```
--------------------------------
### Construct and return SNMPv3 User instance
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/examples/async/get-v3.md
Creates and returns a `User` object using the extracted username, authentication algorithm, authentication key, privacy algorithm, and privacy key. This object encapsulates the SNMPv3 security context.
```python
return User(
username=username,
auth_alg=auth_alg,
auth_key=auth_key,
priv_alg=priv_alg,
priv_key=priv_key,
)
```
--------------------------------
### Run SNMP v2c GETBULK Benchmarks
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/benchmarks/v2c/getbulk_p.md
Execute the pytest suite for benchmarking SNMP v2c GETBULK requests with a concurrency of 4.
```bash
pytest benchmarks/test_v2c_p4_getnext.py
```
--------------------------------
### Run SNMP v3 GETBULK Benchmarks
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/benchmarks/v3/getbulk_p.md
Execute the benchmark tests for SNMP v3 GETBULK requests using pytest. This command initiates the performance evaluation suite.
```bash
pytest benchmarks/test_v3_p4_getbulk.py
```
--------------------------------
### Async SNMPd Daemon Wrapper
Source: https://github.com/gufolabs/gufo_snmp/blob/master/README.md
Run a local instance of an SNMP daemon using the Snmpd wrapper. This is useful for testing SNMP client functionality without a separate daemon.
```python
from gufo.snmp import SnmpSession, Snmpd
async with Snmpd(), SnmpSession(addr="127.0.0.1", port=10161) as session:
r = await session.get("1.3.6.1.2.1.1.3.0")
```
--------------------------------
### Import SnmpSession and User for SNMPv3
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/examples/async/engine-id-discovery.md
Import SnmpSession from gufo.snmp and the User class for SNMPv3 operations. SnmpSession holds the necessary API for SNMP interactions.
```python
from gufo.snmp import SnmpSession, User
```
--------------------------------
### Define Authentication Algorithm Mappings
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/examples/async/get-v3.md
Maps human-readable authentication algorithm names (e.g., 'md5', 'sha') to their corresponding Gufo SNMP classes. This allows for flexible configuration based on string inputs.
```python
AUTH_ALG = {
"no_auth": NoAuth,
"md5": MD5,
"sha": SHA,
}
```
--------------------------------
### Extract authentication algorithm and key from CLI arguments
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/examples/async/get-v3.md
Parses the authentication algorithm name and its corresponding key from command-line arguments. The key is encoded to bytes if provided; otherwise, it defaults to None.
```python
auth_alg_name = sys.argv[2]
auth_key = sys.argv[3].encode() if len(sys.argv) > 3 else None
```
--------------------------------
### Configure SnmpSession for v3
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/examples/sync/get-v3.md
Configure the SnmpSession with agent address and v3 user credentials. This snippet sets up the necessary parameters for a v3 SNMP communication.
```python
session = SnmpSession(agentAddress=agentAddress, user=get_user(userName, authKey, privKey))
```
--------------------------------
### Import asyncio for running async code
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/examples/async/engine-id-discovery.md
When running asynchronous code from a synchronous script, import the asyncio module to use asyncio.run().
```python
import asyncio
```
--------------------------------
### Run Test Suite
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/dev/testing.md
Executes the project's test suite using pytest.
```shell
pytest -vv
```
--------------------------------
### Async Fetch Request
Source: https://github.com/gufolabs/gufo_snmp/blob/master/README.md
Use the fetch method to automatically choose between GETNEXT and GETBULK requests. This simplifies MIB traversal by abstracting the request type.
```python
async with SnmpSession(addr="127.0.0.1", community="public") as session:
async for oid, value in session.fetch("1.3.6.1.2.1.1"):
...
```
--------------------------------
### Create SnmpSession with rate limiting
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/examples/async/ratelimit.md
Instantiate SnmpSession, configuring it to limit outgoing requests per second using the `limit_rps` parameter. This helps prevent overwhelming network devices. The session can be used directly or as an async context manager.
```python
async with SnmpSession(address, community, limit_rps=10) as session:
pass
```
--------------------------------
### Import Snmpd wrapper
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/examples/async/debugging.md
The Snmpd wrapper, used for managing the local snmpd instance, should be imported directly from gufo.snmp.snmpd.
```python
from gufo.snmp.snmpd import Snmpd
```
--------------------------------
### Check Python Code Formatting
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/dev/testing.md
Checks the formatting of Python code in examples/, src/, and tests/ directories without making changes. This is a mandatory requirement for code quality.
```shell
ruff format --check examples/ src/ tests/
```
--------------------------------
### Generate HTML Code Coverage Report
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/dev/testing.md
Generates an HTML report for line-by-line code coverage. Open the 'dist/coverage/index.html' file in a browser to view the report.
```shell
coverage html
```
--------------------------------
### Run Tests for Coverage
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/dev/testing.md
Runs the test suite using pytest with coverage collection enabled. This is the first step to evaluate code coverage.
```shell
coverage run -m pytest -vv
```
--------------------------------
### Run SNMP v3 GETNEXT Benchmarks
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/benchmarks/v3/getnext.md
Execute the benchmark tests for SNMP v3 GETNEXT functionality using pytest. Ensure you have the necessary test files and environment configured.
```bash
pytest benchmarks/test_v3_getnext.py
```
--------------------------------
### Initialize SnmpSession for SNMPv3
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/examples/async/get-v3.md
This snippet shows how to initialize an SnmpSession object, configuring it with agent address, SNMP version, and security parameters for SNMPv3. It's used when establishing a connection to an SNMP agent.
```python
async with SnmpSession(host=address, version=3, security=get_user(username, auth_key, priv_key)) as session:
pass
```
--------------------------------
### Define asynchronous main function
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/examples/async/ratelimit.md
Define an asynchronous function `main` that accepts the agent's address, SNMP community, and base OID as arguments. This function will contain the core SNMP polling logic.
```python
async def main(address: str, community: str, oid: str):
pass
```
--------------------------------
### Map authentication algorithm name to Gufo SNMP class
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/examples/async/get-v3.md
Looks up the appropriate Gufo SNMP authentication algorithm class (e.g., `MD5`, `SHA`) based on the provided algorithm name string.
```python
auth_alg = AUTH_ALG.get(auth_alg_name)
```
--------------------------------
### ASCII + HEX Output Format (-OT)
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/man/gufo-snmp.md
Displays SNMP strings with both human-readable ASCII and hexadecimal representations. Provides a comprehensive view of string data.
```text
1.3.6.1.2.1.1.6.0 = Gufo SNMP Test 47 75 66 6F 20 53 4E 4D 50 20 54 65 73 74
```
--------------------------------
### Async GETBULK Request
Source: https://github.com/gufolabs/gufo_snmp/blob/master/README.md
Retrieve multiple MIB entries efficiently using the GETBULK request. This is often preferred over GETNEXT for large MIBs.
```python
async with SnmpSession(addr="127.0.0.1", community="public") as session:
async for oid, value in session.getbulk("1.3.6.1.2.1.1"):
...
```
--------------------------------
### Import typing module
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/examples/sync/getmany.md
Import required type hints from Python's `typing` module for better code clarity and maintainability.
```Python
from typing import List
```
--------------------------------
### Define an asynchronous main function
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/examples/async/engine-id-discovery.md
Define an async function to handle asynchronous operations. This function expects the agent's address and a valid username as arguments.
```python
async def main(address: str, username: str):
pass
```
--------------------------------
### Extract privacy algorithm and key from CLI arguments
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/examples/async/get-v3.md
Parses the privacy algorithm name and its key from command-line arguments, defaulting to 'no_priv' if not specified. The key is encoded to bytes if provided.
```python
priv_alg_name = sys.argv[4] if len(sys.argv) > 4 else "no_priv"
priv_key = sys.argv[5].encode() if len(sys.argv) > 5 else None
```
--------------------------------
### Without Separator Output (-Qq)
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/man/gufo-snmp.md
Formats SNMP output without an '=' separator between the OID and its value. Useful for simplified parsing.
```text
1.3.6.1.2.1.1.6.0 Gufo SNMP Test
```
--------------------------------
### ASCII Output Format (-Oa)
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/man/gufo-snmp.md
Prints SNMP strings in ASCII format, replacing non-printable characters with dots. Use this for human-readable text output.
```text
1.3.6.1.2.1.1.6.0 = Gufo SNMP Test
```
--------------------------------
### Import SnmpSession from gufo.snmp
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/examples/async/debugging.md
The SnmpSession object contains the necessary API for SNMP operations. Import it from the gufo.snmp module.
```python
from gufo.snmp import SnmpSession
```
--------------------------------
### Import sys for CLI arguments
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/examples/async/engine-id-discovery.md
Import the sys module to parse command-line arguments. For real-world applications, consider using argparse or similar libraries.
```python
import sys
```
--------------------------------
### Python Script for Engine ID Discovery
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/examples/sync/engine-id-discovery.md
This script demonstrates how to discover the SNMPv3 Engine ID for a given agent address and username using Gufo SNMP. It imports necessary modules and sets up the SNMP session.
```python
import sys
from gufo.snmp.sync_client import SnmpSession
from gufo.snmp.user import User
def main(address: str, username: str):
# Create SnmpSession object
with SnmpSession(address=address, user=User(username=username)) as session:
# Get Engine ID
engine_id = session.get_engine_id()
# Print Engine ID in hexadecimal format
print(engine_id.hex())
if __name__ == "__main__":
# Get address and username from command-line arguments
agent_address = sys.argv[1]
user_name = sys.argv[2]
main(agent_address, user_name)
```
--------------------------------
### Value Only Output (-Ov)
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/man/gufo-snmp.md
Displays only the value of the SNMP variable, omitting the OID. Ideal for scripts that only need the data itself.
```text
Gufo SNMP Test
```
--------------------------------
### Define Privacy Algorithm Mappings
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/examples/async/get-v3.md
Maps human-readable privacy algorithm names (e.g., 'des', 'aes128') to their corresponding Gufo SNMP classes. This enables dynamic selection of encryption algorithms.
```python
PRIV_ALG = {
"no_priv": NoPriv,
"des": DES,
"aes128": AES128,
}
```
--------------------------------
### Process and print results
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/examples/sync/getmany.md
Iterate through the results dictionary and print each OID and its corresponding value. Note that `get_many()` ignores non-existent OIDs.
```Python
for oid, value in results.items():
print(f"{oid}: {value}")
```
--------------------------------
### Create SnmpSession with SNMPv3 User
Source: https://github.com/gufolabs/gufo_snmp/blob/master/docs/examples/async/engine-id-discovery.md
Create an SnmpSession object to manage the client's session. It can be used directly or as an async context manager. For SNMPv3, create a User object with the username. The username is the only mandatory parameter for Engine ID discovery.
```python
async with SnmpSession(address=address, user=User(username=username)) as session:
pass
```