ubuntu 20.04 snmp 配置 agentx python3

本文档详细介绍了在Ubuntu 20.04上配置SNMP AgentX以及使用Python3进行SNMP操作的步骤,包括安装SNMP、SNMP AgentX模块pyagentx3,解决编码错误问题,以及使用pysnmp库进行SNMP GET和SET操作。同时,展示了如何配置SNMPd和snmptrapd服务,并提供了配置文件示例。

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

<think>我们正在处理一个关于在Ubuntu 20.04上手动安装和配置Python2的问题。 根据引用[1]和引用[2]的内容,我们知道Ubuntu 20.04默认移除了Python2,但有时我们仍然需要它。 因此,我们需要手动安装Python2.7,并配置系统,使得我们可以使用Python2和Python3,并且可以手动切换默认版本(如果需要)。 注意:在Ubuntu 20.04中,系统的一些组件已经依赖于Python3,因此我们不建议将系统默认的Python切换为Python2,而是使用替代方法(如虚拟环境或显式使用python2命令)来运行Python2程序。 但是,根据用户要求,我们需要提供手动安装和配置Python2的指导,包括如何设置默认版本(如果用户需要的话)。 步骤概览: 1. 安装Python2.7 2. 安装pip for Python2(可选,但推荐) 3. 配置Python版本(使用update-alternatives)以便在系统中有多个Python版本时进行切换(注意:系统关键命令`python`可能指向Python2或Python3,但Ubuntu20.04默认没有`python`命令,我们需要配置一个) 注意:在Ubuntu20.04中,默认情况下,`python`命令是没有被设置的,因为系统希望用户明确使用`python3`或`python2`。但是,我们可以通过update-alternatives来设置`python`命令指向哪个版本。 详细步骤: 步骤1:安装Python2.7 由于官方源已经移除了Python2,我们需要从universe仓库中安装,或者添加其他源。但通常,我们可以直接安装python2.7包(在20.04中仍然可用,但可能不在主仓库?实际上,在20.04中,python2.7包仍然存在于universe仓库中,我们可以启用universe仓库并安装) 首先,确保universe仓库启用: sudo add-apt-repository universe sudo apt update 然后安装Python2.7: sudo apt install python2.7 步骤2:安装pip for Python2 curl -O https://bootstrap.pypa.io/pip/2.7/get-pip.py sudo python2.7 get-pip.py 步骤3配置Python版本(可选,设置默认的`python`命令) 注意:在Ubuntu20.04中,系统本身没有设置`python`命令,以避免混淆。但是,我们可以通过`update-alternatives`来管理。 首先,为python2.7和python3(假设已经安装了python3)设置替代项: 安装python3(如果尚未安装): sudo apt install python3 添加python2和python3到update-alternatives系统: sudo update-alternatives --install /usr/bin/python python /usr/bin/python2.7 1 sudo update-alternatives --install /usr/bin/python python /usr/bin/python3.8 2 # 注意:Ubuntu20.04默认的Python3版本是3.8 然后,我们可以通过以下命令切换默认的python版本: sudo update-alternatives --config python 然后选择数字(1对应python2.7,2对应python3.8) 警告:将系统默认的python指向python2可能会破坏一些系统工具,因为Ubuntu20.04的系统脚本通常使用python3。因此,建议仅在用户级使用,或者使用虚拟环境。 替代方案:使用别名(alias)或者在运行命令时显式使用python2或python3。 步骤4:测试 python --version # 查看当前默认的python版本 python2 --version # 应该显示Python2.7.x python3 --version # 应该显示Python3.8.x 但是,如果用户不需要全局更改默认的python命令,可以跳过步骤3,而直接使用python2命令来运行Python2脚本。 另外,建议使用虚拟环境(virtualenv)来管理不同项目所需的Python环境。 安装virtualenv(对于Python2和Python3): 对于Python2:使用pip2安装virtualenv sudo pip2 install virtualenv 对于Python3:使用pip3安装virtualenv(或者使用venv模块,但venv是Python3内置的) sudo pip3 install virtualenv 然后,为Python2项目创建虚拟环境: virtualenv -p python2 myenv2 激活虚拟环境: source myenv2/bin/activate 这样,在虚拟环境中,python命令就是Python2了。 总结:我们提供了两种方式使用Python2:一种是全局配置(但不推荐,因为可能影响系统),另一种是使用虚拟环境(推荐)。 根据用户要求,我们提供了手动安装和配置Python2的步骤,包括设置默认版本(可选)和安装pip。 注意:在安装过程中,如果遇到问题,比如依赖关系错误,可以使用`sudo apt -f install`来修复。 下面,我们将按照上述步骤写出详细的指导。</think>以下是Ubuntu 20.04手动安装和配置Python 2的详细指南,基于系统兼容性和安全性最佳实践: ### 一、Python 2安装步骤 1. **启用Universe仓库** ```bash sudo add-apt-repository universe sudo apt update ``` 2. **安装Python 2.7核心包** ```bash sudo apt install python2.7 -y ``` 3. **安装pip for Python 2** ```bash curl -O https://bootstrap.pypa.io/pip/2.7/get-pip.py sudo python2.7 get-pip.py ``` ### 二、版本配置方案 #### 方案A:虚拟环境(推荐) ```bash # 安装虚拟环境工具 sudo apt install virtualenv # 创建Python2专用环境 virtualenv --python=python2.7 py2_env # 激活环境 source py2_env/bin/activate ``` > 此时终端提示符会显示`(py2_env)`,所有命令自动指向Python 2.7[^1] #### 方案B:全局版本切换(谨慎使用) ```bash # 注册Python版本到系统备选项 sudo update-alternatives --install /usr/bin/python python /usr/bin/python2.7 1 sudo update-alternatives --install /usr/bin/python python /usr/bin/python3 2 # 交互式选择版本 sudo update-alternatives --config python ``` > 选择后通过`python --version`验证,**注意**:可能影响系统工具链[^2] ### 三、关键配置验证 1. **检查Python版本** ```bash python2.7 -V # 应输出 Python 2.7.x ``` 2. **测试pip工作状态** ```bash pip2 install requests # 安装Python2专用包 python2 -c "import requests; print(requests.__version__)" ``` ### 四、兼容性处理 1. **修复常见依赖问题** ```bash # 安装缺失的SSL模块 sudo apt install libssl1.1 -y ``` 2. **处理编码问题** 在脚本开头添加: ```python # -*- coding: utf-8 -*- import sys reload(sys) sys.setdefaultencoding(&#39;utf8&#39;) ``` ### 五、注意事项 1. **安全警告** Python 2已于2020年停止官方支持,仅应在隔离环境中使用[^1] 2. **系统保护措施** ```bash # 恢复系统默认Python3链接 sudo ln -sf /usr/bin/python3 /usr/bin/python ``` > 对于长期项目,建议使用Docker容器封装Python2环境: > `docker run -it ubuntu:18.04 python2.7`(Ubuntu 18.04是最后官方支持Python2的LTS版本)
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值