ubuntu 20.04 snmp 配置 agentx python3

ubuntu 20.04 snmp 配置 agentx python3

Ubuntu20.04安装python2和python3及版本配置

https://blog.youkuaiyun.com/pangc2014/article/details/117407413

对应的 agentx3

https://pypi.org/project/pyagentx3/
https://github.com/rprinz08/pyagentx3

sudo apt install snmpd snmptrapd snmp-mibs-downloader

遇到问题

Unhandled exception: ‘latin-1’ codec can’t encode character ‘\u5ea6’ in position 44: ordinal not in range(256)
2022-04-14 00:58:16,826 - pyagentx3.updater - INFO - Updater stopping

sudo pip3 install redis

file = open(“xxx.txt”,“r”,encoding=“utf-8”)

for line in file:
line=line.encode(“utf-8”).decode(“latin1”)
print(line)

pysnmp

https://pypi.org/project/pysnmp/
https://github.com/etingof/pysnmp

pip install pysnmp
在这里插入图片描述
sudo pip3 install snmpclitools

snmpget.py -v 2c -c public 192.168.99.32 1.3.6.1.4.1.77587.1827

D
jack@ubuntu:~/swork_snmp$ snmpget.py -v 2c -c public 192.168.99.32 1.3.6.1.4.1.77587.1827
SNMPv2-SMI::enterprises.77587.1827 = OctetString: 0x7b226669656c645f6e616d65223a20227361745f696e666f3230222c202276616c7565223a20223130302e3530e5baa62c2031323734392e3735304d487a2c20e59e82e79bb4e69e81e58c96222c202274696d657374616d70223a20313634393932343430322e393835343134357d

pysnmp get1

from pysnmp.hlapi import *

iterator = getCmd(SnmpEngine(),
                  CommunityData('public'),
                  UdpTransportTarget(('192.168.99.32', 161)),
                  ContextData(),
                  ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0)))

errorIndication, errorStatus, errorIndex, varBinds = next(iterator)

if errorIndication:  # SNMP engine errors
    print(errorIndication)
else:
    if errorStatus:  # SNMP agent errors
        print('%s at %s' % (errorStatus.prettyPrint(), varBinds[int(errorIndex)-1] if errorIndex else '?'))
    else:
        for varBind in varBinds:  # SNMP response contents
            print(' = '.join([x.prettyPrint() for x in varBind]))

pysnmp get2

from pysnmp.hlapi import *

iterator = getCmd(SnmpEngine(),
                  CommunityData('public'),
                  UdpTransportTarget(('192.168.99.32', 161)),
                  ContextData(),
                  ObjectType(ObjectIdentity('1.3.6.1.4.1.77587.1765')))

errorIndication, errorStatus, errorIndex, varBinds = next(iterator)

if errorIndication:  # SNMP engine errors
    print(errorIndication)
else:
    if errorStatus:  # SNMP agent errors
        print('%s at %s' % (errorStatus.prettyPrint(), varBinds[int(errorIndex)-1] if errorIndex else '?'))
    else:
        for varBind in varBinds:  # SNMP response contents
            print(' = '.join([x.prettyPrint() for x in varBind]))

python3中pysnmp八位字符串到hex的转换

<class 'pysnmp.smi.rfc1902.ObjectType'>
[ObjectIdentity(<ObjectName value object, tagSet <TagSet object, tags 0:0:6>, payload [1.3.6.1.4.1.77587.1827]>), <OctetString value object, tagSet <TagSet object, tags 0:0:4>, subtypeSpec <ConstraintsIntersection object, consts <ValueSizeConstraint object, consts 0, 65535>>, encoding iso-8859-1, payload [0x7b226669656c64...2e3835343737387d]>]

11

from pysnmp.hlapi import *

iterator = getCmd(SnmpEngine(),
                  CommunityData('public'),
                  UdpTransportTarget(('192.168.99.32', 161)),
                  ContextData(),
                  ObjectType(ObjectIdentity('1.3.6.1.4.1.77587.1827')))

errorIndication, errorStatus, errorIndex, varBinds = next(iterator)

if errorIndication:  # SNMP engine errors
    print(errorIndication)
else:
    if errorStatus:  # SNMP agent errors
        print('%s at %s' % (errorStatus.prettyPrint(), varBinds[int(errorIndex)-1] if errorIndex else '?'))
    else:
        for varBind in varBinds:  # SNMP response contents
            print("\n+++++++++++++++++++++\n")
            #print(varBind)
            print(type(varBind))

            print([x for x in varBind])
            print("\n-----------1111-------------\n")
            print(str(varBind))
            print(tuple(varBind))
            print(str(tuple(varBind)[1]).encode("latin1").decode("utf-8"))
            print("\n-----------22222-------------\n")
            print(' = '.join([x.prettyPrint() for x in varBind]))

@@@

-----------1111-------------

SNMPv2-SMI::enterprises.77587.1827 = 0x7b226669656c645f6e616d65223a20227361745f696e666f3230222c202276616c7565223a20223130302e3530e5baa62c2031323734392e3735304d487a2c20e59e82e79bb4e69e81e58c96222c202274696d657374616d70223a20313634393932393136392e303531393635357d
(ObjectIdentity(<ObjectName value object, tagSet <TagSet object, tags 0:0:6>, payload [1.3.6.1.4.1.77587.1827]>), <OctetString value object, tagSet <TagSet object, tags 0:0:4>, subtypeSpec <ConstraintsIntersection object, consts <ValueSizeConstraint object, consts 0, 65535>>, encoding iso-8859-1, payload [0x7b226669656c64...303531393635357d]>)
{"field_name": "sat_info20", "value": "100.50度, 12749.750MHz, 垂直极化", "timestamp": 1649929169.0519655}

-----------22222-------------

22

    --------
        >>> from pysnmp.proto.rfc1902 import *
        >>> ObjectIdentifier((1, 3, 6))
        ObjectIdentifier('1.3.6')
        >>> ObjectIdentifier('1.3.6')
        ObjectIdentifier('1.3.6')
        >>> tuple(ObjectIdentifier('1.3.6'))
        (1, 3, 6)
        >>> str(ObjectIdentifier('1.3.6'))
        '1.3.6'
        >>>

    """

local-agent.py snmpset

/home/jack/swork_snmp/PyAgentX3-master/samples/
sudo python local-agent.py

snmpwalk -v 2c -c public localhost 1.3.6.1.4.1.8072.2.1

NET-SNMP-EXAMPLES-MIB::netSnmpExampleInteger.0 = INTEGER: 9000
NET-SNMP-EXAMPLES-MIB::netSnmpExampleSleeper.0 = INTEGER: 0
NET-SNMP-EXAMPLES-MIB::netSnmpExampleString.0 = STRING: String for NET-SNMP-EXAMPLES-MIB
NET-SNMP-EXAMPLES-MIB::netSnmpExampleScalars.4.0 = OID: SNMPv2-SMI::private.6.7
NET-SNMP-EXAMPLES-MIB::netSnmpExampleScalars.5.0 = IpAddress: 192.168.0.1
NET-SNMP-EXAMPLES-MIB::netSnmpExampleScalars.6.0 = Counter32: 2000
NET-SNMP-EXAMPLES-MIB::netSnmpExampleScalars.7.0 = Gauge32: 2000
NET-SNMP-EXAMPLES-MIB::netSnmpExampleScalars.8.0 = Timeticks: (31199) 0:05:11.99
NET-SNMP-EXAMPLES-MIB::netSnmpExampleScalars.9.0 = OPAQUE: 54 65 73 74
NET-SNMP-EXAMPLES-MIB::netSnmpExampleScalars.10.0 = Counter64: 32

snmpget -v 2c -c public localhost 1.3.6.1.4.1.8072.2.1.3.0
NET-SNMP-EXAMPLES-MIB::netSnmpExampleString.0 = STRING: String for NET-SNMP-EXAMPLES-MIB
snmpget -v 2c -c public localhost NET-SNMP-EXAMPLES-MIB::netSnmpExampleString.0
NET-SNMP-EXAMPLES-MIB::netSnmpExampleString.0 = STRING: String for NET-SNMP-EXAMPLES-MIB

snmpset -v 2c -c public localhost NET-SNMP-EXAMPLES-MIB::netSnmpExampleInteger.0 i 10
snmpset -v 2c -c public localhost NET-SNMP-EXAMPLES-MIB::netSnmpExampleInteger.0 i 200
snmpset -v 2c -c public localhost NET-SNMP-EXAMPLES-MIB::netSnmpExampleString.0 s “Test”

snmpset -v 2c -c public localhost 1.3.6.1.4.1.8072.2.1.1.0 10

1.3.6.1.4.1.8072.2.1.1.0

snmpget -v 2c -c public localhost 1.3.6.1.4.1.8072.2.1.1.0
NET-SNMP-EXAMPLES-MIB::netSnmpExampleInteger.0 = INTEGER: 9000

snmpset -v 1 -c private localhost 1.3.6.1.4.1.8072.2.1.1.0 i 10
NET-SNMP-EXAMPLES-MIB::netSnmpExampleInteger.0 = INTEGER: 10
在这里插入图片描述

snmpset -v 2c -c public localhost 1.3.6.1.4.1.8072.2.1.1.0 i 42
在这里插入图片描述
在这里插入图片描述

#
# snmpd.conf
# An example configuration file for configuring the Net-SNMP agent ('snmpd')
# See snmpd.conf(5) man page for details
#
###########################################################################
# SECTION: System Information Setup
#

# syslocation: The [typically physical] location of the system.
#   Note that setting this value here means that when trying to
#   perform an snmp SET operation to the sysLocation.0 variable will make
#   the agent return the "notWritable" error code.  IE, including
#   this token in the snmpd.conf file will disable write access to
#   the variable.
#   arguments:  location_string
sysLocation    Sitting on the Dock of the Bay
sysContact     Me <me@example.org>

# sysservices: The proper value for the sysServices object.
#   arguments:  sysservices_number
sysServices    72



###########################################################################
# SECTION: Agent Operating Mode
#
#   This section defines how the agent will operate when it
#   is running.

# master: Should the agent operate as a master agent or not.
#   Currently, the only supported master agent type for this token
#   is "agentx".
#
#   arguments: (on|yes|agentx|all|off|no)

master  agentx
#agentxSocket tcp:localhost:705

#agentxTimeout 5000

#agentxRetries 0
# agentaddress: The IP address and port number that the agent will listen on.
#   By default the agent listens to any and all traffic from any
#   interface on the default SNMP port (161).  This allows you to
#   specify which address, interface, transport type and port(s) that you
#   want the agent to listen on.  Multiple definitions of this token
#   are concatenated together (using ':'s).
#   arguments: [transport:]port[@interface/address],...

#agentaddress  127.0.0.1,[::1]
agentAddress udp:161


###########################################################################
# SECTION: Access Control Setup
#
#   This section defines who is allowed to talk to your running
#   snmp agent.

# Views
#   arguments viewname included [oid]

#  system + hrSystem groups only
view   systemonly  included   .1.3.6.1.2.1.1
view   systemonly  included   .1.3.6.1.2.1.25.1
view   systemonly  included   .1.3.6.1.4.1.77587
view   systemonly  included   .1.3.6.1.4.1.8072.2


# rocommunity: a SNMPv1/SNMPv2c read-only access community name
#   arguments:  community [default|hostname|network/bits] [oid | -V view]

# Read-only access to everyone to the systemonly view
#rocommunity  public default -V systemonly
#rocommunity6 public default -V systemonly
#
rocommunity  public default
rwcommunity  private default
rocommunity6  public default
rwcommunity6  private default

# SNMPv3 doesn't use communities, but users with (optionally) an
# authentication and encryption string. This user needs to be created
# with what they can view with rouser/rwuser lines in this file.
#

trap

apt install snmpd snmptrapd snmp-mibs-downloader
在这里插入图片描述
sudo service snmpd restart

sudo python local-agent.py

sudo snmptrapd -c /etc/snmp/snmptrapd.conf -f -Lo -d
在这里插入图片描述

配置文件内容 sudo cat snmpd.conf

###########################################################################
#
# snmpd.conf
# An example configuration file for configuring the Net-SNMP agent ('snmpd')
# See snmpd.conf(5) man page for details
#
###########################################################################
# SECTION: System Information Setup
#

# syslocation: The [typically physical] location of the system.
#   Note that setting this value here means that when trying to
#   perform an snmp SET operation to the sysLocation.0 variable will make
#   the agent return the "notWritable" error code.  IE, including
#   this token in the snmpd.conf file will disable write access to
#   the variable.
#   arguments:  location_string
sysLocation    Sitting on the Dock of the Bay
sysContact     Me <me@example.org>

# sysservices: The proper value for the sysServices object.
#   arguments:  sysservices_number
sysServices    72



###########################################################################
# SECTION: Agent Operating Mode
#
#   This section defines how the agent will operate when it
#   is running.

# master: Should the agent operate as a master agent or not.
#   Currently, the only supported master agent type for this token
#   is "agentx".
#
#   arguments: (on|yes|agentx|all|off|no)
#
#
#
#trap2sink    localhost public                                    #   send SNMPv1  traps
trapsink     localhost public

                                   # generate traps on UCD error conditions
defaultMonitors          yes
                                   # generate traps on linkUp/Down
linkUpDownNotifications  yes



master  agentx
#agentxSocket tcp:localhost:705

#agentxTimeout 5000

#agentxRetries 0
# agentaddress: The IP address and port number that the agent will listen on.
#   By default the agent listens to any and all traffic from any
#   interface on the default SNMP port (161).  This allows you to
#   specify which address, interface, transport type and port(s) that you
#   want the agent to listen on.  Multiple definitions of this token
#   are concatenated together (using ':'s).
#   arguments: [transport:]port[@interface/address],...

#agentaddress  127.0.0.1,[::1]
agentAddress udp:161


###########################################################################
# SECTION: Access Control Setup
#
#   This section defines who is allowed to talk to your running
#   snmp agent.

# Views
#   arguments viewname included [oid]

#  system + hrSystem groups only
view   systemonly  included   .1.3.6.1.2.1.1
view   systemonly  included   .1.3.6.1.2.1.25.1
view   systemonly  included   .1.3.6.1.4.1.77587
view   systemonly  included   .1.3.6.1.4.1.8072.2


# rocommunity: a SNMPv1/SNMPv2c read-only access community name
#   arguments:  community [default|hostname|network/bits] [oid | -V view]

# Read-only access to everyone to the systemonly view
#rocommunity  public default -V systemonly
#rocommunity6 public default -V systemonly
#
rocommunity  public default
rwcommunity  private default
rocommunity6  public default
rwcommunity6  private default

# SNMPv3 doesn't use communities, but users with (optionally) an
# authentication and encryption string. This user needs to be created
# with what they can view with rouser/rwuser lines in this file.
#
# createUser username (MD5|SHA|SHA-512|SHA-384|SHA-256|SHA-224) authpassphrase [DES|AES] [privpassphrase]
# e.g.
# createuser authPrivUser SHA-512 myauthphrase AES myprivphrase
#
# This should be put into /var/lib/snmp/snmpd.conf
#
# rouser: a SNMPv3 read-only access username
#    arguments: username [noauth|auth|priv [OID | -V VIEW [CONTEXT]]]
rouser authPrivUser authpriv -V systemonly

sudo cat snmptrapd.conf



#
# EXAMPLE-trap.conf:
#   An example configuration file for configuring the Net-SNMP snmptrapd agent.
#
###############################################################################
#
# This file is intended to only be an example.
# When the snmptrapd agent starts up, this is where it will look for it.
#
# All lines beginning with a '#' are comments and are intended for you
# to read.  All other lines are configuration commands for the agent.

#
# PLEASE: read the snmptrapd.conf(5) manual page as well!
#
#authCommunity log,execute,net private 
#authCommunity log,execute,net public
#
authCommunity log public
## send mail when get any events
#traphandle default /usr/bin/traptoemail -s smtp.example.org foobar@example.org
#
## send mail when get linkDown
#traphandle .1.3.6.1.6.3.1.1.5.3 /usr/bin/traptoemail -s smtp.example.org foobar@example.org

### 创建指向 Python 3 的软连接 在 Ubuntu 20.04 中,默认情况下 `python` 命令可能未被设置为指向 Python 3,而是指向 `/usr/bin/python` 或其他路径。如果希望将 `python` 命令默认映射到 Python 3,则可以通过创建符号链接来实现。 #### 使用 `ln` 命令创建软连接 可以使用以下命令手动创建一个符号链接,使 `python` 指向 Python 3: ```bash sudo ln -sf /usr/bin/python3 /usr/bin/python ``` 此命令会强制覆盖已存在的符号链接(如果有),并将 `python` 设置为指向 `/usr/bin/python3`[^2]。 #### 验证软连接是否生效 执行以下命令验证当前使用的 Python 版本以及其实际路径: ```bash python --version which python ``` 正常情况下,输出应显示如下内容: ``` Python 3.x.x /usr/bin/python ``` 这表明 `python` 已成功指向 Python 3[^2]。 #### 更推荐的方法:使用 `update-alternatives` 另一种更为安全的方式是通过系统的 `update-alternatives` 工具管理多个版本的 Python 解释器。这种方法不会直接覆盖现有的符号链接,而是允许动态切换不同版本的解释器。 以下是具体步骤: 1. 添加 Python 3 到 alternatives 系统中: ```bash sudo update-alternatives --install /usr/bin/python python /usr/bin/python3 1 ``` 2. 如果存在多个 Python 版本,可通过以下命令选择所需的默认版本: ```bash sudo update-alternatives --config python ``` 此时可以选择让 `python` 指向哪个具体的 Python 可执行文件[^3]。 #### 注意事项 - 修改全局符号链接可能会影响依赖于旧版 Python 的系统工具或脚本。因此,在更改之前建议备份原始状态并测试变更后的行为。 - 对于开发用途,强烈建议使用虚拟环境(如 venv 或 conda)隔离项目所需的具体 Python 版本及其库集合[^3]。 ```bash # 示例:基于 venv 创建独立的 Python 虚拟环境 python3 -m venv myenv source myenv/bin/activate ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值