One place for hosting & domains

      Como instalar e configurar um daemon e cliente SNMP no Ubuntu 18.04


      O autor selecionou Internet Archive para receber uma doação como parte do programa Write for DOnations.

      Introdução

      Grande parte de ser um administrador de sistemas é coletar informações precisas de seus servidores e infraestrutura. Existe um grande número de ferramentas e opções para a reunião e processamento deste tipo de informação. Muitas delas são construídas em uma tecnologia chamada SNMP.

      SNMP significa protocolo simples de gerência de rede. É uma maneira que os servidores podem compartilhar informações sobre o estado atual deles, e também um canal através do qual um administrador pode modificar valores pré-definidos. Embora o protocolo em si seja leve, a estrutura de programas que implementam o SNMP pode ser bastante complexa. Para obter mais informações sobre o básico do protocolo SNMP, consulte nosso artigo de Introdução ao SNMP.

      Neste guia, você configurará as ferramentas para se comunicar usando o SNMP. Você usará dois servidores Ubuntu 18.04. para uma demonstração. Um deles terá o SNMP manager, que dirá ao agente para implementar dispositivos de rede. Este servidor será chamado de manager server. O outro servidor terá o SNMP agent, que agirá conforme as ordens do servidor gerente. Este servidor será chamado de agent server. Você pode escolher instalar o agente na máquina do gerente também. Porém, mantê-los separados torna mais fácil demonstrar qual funcionalidade é fornecida por cada componente.

      Pré-requisitos

      Para seguir este tutorial, você vai precisar do seguinte:

      Passo 1 — Instalando o daemon e utilitários SNMP

      Comece a explorar como o SNMP pode ser implementado em um sistema instalando o daemon e as ferramentas em seus servidores Ubuntu.

      A partir de sua máquina local, faça login no manager server como seu usuário não raiz:

      • ssh your_username@manager_server_ip_address

      Atualize o índice do pacote para o gerenciador de pacotes do APT:

      Em seguida, instale o software SNMP:

      • sudo apt install snmp snmp-mibs-downloader

      O pacote snmp fornece uma coleção de ferramentas de linha de comando para a emissão de solicitações SNMP a agentes. O pacote snmp-mibs-downloader ajudará a instalar e gerenciar os arquivos da Base de informações de gerenciamento (MIB), que monitora os objetos de rede.

      Então, abra um novo terminal em sua máquina local e faça login no agent server:

      • ssh your_username@agent_server_ip_address

      Em agent server, atualize o índice do pacote:

      Em seguida, instale o daemon SNMP.

      Note que você não precisa do pacote snmp-mibs-downloader, pois o agent server não gerenciará os arquivos MIB.

      Agora que instalou esses componentes, você configurará seu manager server.

      Passo 2 — Configurando o servidor gerente do SNMP

      Como mencionado anteriormente, a maioria dos trabalhos acontece no agent server. Por este motivo, sua configuração no manager server será mais simples. Você precisa modificar um arquivo para garantir que as ferramentas do SNMP possam usar os dados extras do MIB instalados.

      Em seu manager server, abra o arquivo /etc/snmp/snmp.conf em seu editor de texto com privilégios sudo. Este tutorial usará o nano.

      • sudo nano /etc/snmp/snmp.conf

      Neste arquivo, há alguns comentários e uma única linha descomentada. Para permitir que o gerente importe os arquivos do MIB, deixe a linha mibs : como comentário:

      /etc/snmp/snmp.conf

      # As the snmp packages come without MIB files due to license reasons, loading
      # of MIBs is disabled by default. If you added the MIBs you can reenable
      # loading them by commenting out the following line.
      #mibs :
      

      Salve e feche o snmp.conf pressionando CTRL+X, seguido de Y e, em seguida, ENTER se estiver usando o nano.

      Você acabou de configurar o manager server, mas ainda assim precisará usar este servidor para ajudar a configurar seu agent server, o que você fará no próximo passo.

      Passo 3 — Configurando o servidor agente do SNMP

      Como um verdadeiro sistema de cliente-servidor, o agent server não possui nenhuma das ferramentas externas necessárias para configurar sua própria configuração do SNMP. Você pode modificar alguns arquivos de configuração para fazer algumas alterações, mas a maioria das alterações que precisa fazer serão feitas ao se conectar ao seu agent server, a partir do servidor de gerenciamento.

      Neste tutorial, você usará a versão 3 do protocolo do SNMP. Ao contrário do SNMPv1 e do v2, no SNMPv3, cada mensagem contém parâmetros de segurança que são codificados. Neste passo, você configurará a autenticação e as regras de controle de acesso do SNMPv3.

      Para começar, em seu agent server, abra o arquivo de configuração do daemon com privilégios do sudo:

      • sudo nano /etc/snmp/snmpd.conf

      Dentro dele, você terá que fazer algumas alterações. Esses arquivos serão usados principalmente para a inicialização de sua configuração, para que possa gerenciá-la de seu outro servidor.

      Primeiro, altere a diretiva do agentAddress. Atualmente, ela está definida para permitir apenas conexões originárias do computador local. Será necessário comentar a linha atual e descomentar a linha abaixo dela, que permite todas as conexões.

      /etc/snmp/snmpd.conf

      #  Listen for connections from the local system only
      #agentAddress  udp:127.0.0.1:161
      #  Listen for connections on all interfaces (both IPv4 *and* IPv6)
      agentAddress udp:161,udp6:[::1]:161
      

      Nota: como permitir todas as conexões não é uma boa prática de segurança, é melhor se certificar de reverter isso logo após a conclusão da inicialização.

      Em seguida, insira temporariamente uma linha createUser. Essas diretrizes normalmente não são mantidas neste arquivo; você irá removê-las em instantes.

      O usuário que você está criando será chamado de bootstrap e será usado como modelo para criar seu primeiro usuário real. Os pacotes do SNMP fazem isso através de um processo de clonagem das propriedades do usuário.

      Ao definir um novo usuário, você deve especificar o tipo de autenticação (MD5 ou SHA), assim como fornecer uma senha que deve ter pelo menos oito caracteres. Caso esteja planejando usar criptografia para fazer a transferência, como fará neste tutorial, especifique também o protocolo de privacidade (DES ou AES) e, como opção, uma senha do protocolo de privacidade. Caso nenhuma senha de protocolo de privacidade seja fornecida, será usada a senha de autenticação para o protocolo de privacidade.

      Adicione essa linha createUser ao final do arquivo:

      /etc/snmp/snmpd.conf

      ...
      createUser bootstrap MD5 temp_password DES
      

      Agora que tem um novo usuário especificado, configure o nível de acesso que este usuário terá. Neste tutorial, você configurará este nível de acesso para seu usuário bootstrap e para o novo usuário que criará, chamado de demo. Você permitirá o acesso de leitura e a gravação deles usando a diretiva rwuser (outra alternativa é usar o rouser para acesso de somente leitura).

      Você também aplicará o uso da criptografia, especificando priv após seu usuário. Caso quisesse restringir o usuário a uma parte específica do MIB, você poderia especificar o identificador de objeto (IDO) de mais alto nível ao qual o usuário deve ter de acesso ao final da linha.

      Para fins deste tutorial, ambas as linhas serão como se segue:

      /etc/snmp/snmpd.conf

      ...
      rwuser bootstrap priv
      rwuser demo priv
      

      Quando terminar de fazer essas alterações, salve e feche o arquivo.

      Para implementar essas alterações, reinicie o serviço snmpd em seu agent server:

      • sudo systemctl restart snmpd

      O daemon do SNMP escutará conexões na porta :161. Configure o UFW para permitir conexões do manager server para essa porta:

      • sudo ufw allow from manager_server_ip_address to any port 161

      Aprenda mais sobre o UFW em Como configurar um firewall com o UFW no Ubuntu 18.04.

      Agora que o agent server está configurado, conecte-se ao seu agent server a partir do manager server para verificar a conexão.

      Passo 4 — Verificando a autenticação para o servidor agente

      Neste passo, você fará um teste para garantir que é possível se conectar com sua conta bootstrap ao agent server. No entanto, antes disso, este tutorial falará um pouco a respeito da estrutura geral de se enviar um comando do SNMP.

      Ao usar o conjunto de ferramentas incluídas no pacote snmp (o conjunto de software net-snmp), existem alguns padrões na maneira como se deve chamar os comandos. A primeira coisa a fazer é autenticar-se ao daemon do SNMP que você deseja se comunicar. Normalmente, isso envolve fornecer algumas informações. As mais comuns são as seguintes:

      • -v: este sinalizador é utilizado para especificar a versão do protocolo SNMP que você gostaria de usar. Este tutorial utilizará a v3.
      • -c: este sinalizador é usado caso esteja utilizando a cadeia da comunidade no estilo SNMP v1 ou v2 para a autenticação. Como você está usando a autenticação baseada no usuário no estilo v3, não será necessário fazer isso.
      • -u: este parâmetro é usado para especificar o nome de usuário que você deseja usar para se autenticar. Para ler ou modificar qualquer coisa usando o SNMP, você deve autenticar-se com um nome de usuário conhecido.
      • -l: é usado para especificar o nível de segurança ao qual você está se conectando. Os valores possíveis são noAuthNoPriv para não ter autenticação e nem criptografia, authNoPriv para ter a autenticação, mas não ter criptografia e a authPriv para ter a autenticação e a criptografia. O nome de usuário que está usando deve ser configurado para operar no nível de segurança especificado, ou então a autenticação não será bem sucedida.
      • -a: este parâmetro é usado para especificar o authentication protocol utilizado. Os valores possíveis são o MD5 ou o SHA. Essa informação deve corresponder às informações especificadas quando o usuário foi criado.
      • -x: este parâmetro é usado para especificar o encryption protocol utilizado. Os valores possíveis são DES ou AES. Essa informação deve corresponder às informações especificadas quando o usuário foi criado. Issto é necessário sempre que a especificação de privilégios do usuário tiver um priv depois dela, tornando a criptografia obrigatória.
      • -A: é usado para fornecer a senha de autenticação especificada quando o usuário foi criado.
      • -X: esta é a senha da criptografia especificada quando o usuário foi criado. Caso nenhuma senha tenha sido especificada, mas um algoritmo de criptografia tenha sido dado, será utilizada a senha de autenticação. Isso é necessário quando o parâmetro -x é dado ou sempre que a especificação de privilégios de um usuário tiver um priv depois dela, exigindo uma criptografia.

      Ao usar essas informações, é possível construir seus comandos. Dado que você configurou seu usuário bootstrap, os comandos que você usará com essa conta se parecerão a este:

      snmp_command -u bootstrap -l authPriv -a MD5 -x DES -A temp_password -X temp_password remote_host snmp_sub_command_or_options
      

      A partir de seu manager server, faça um teste para garantir que a conta bootstrap está disponível. Digite o seguinte para exibir as informações de sistema para o agent server:

      • snmpget -u bootstrap -l authPriv -a MD5 -x DES -A temp_password -X temp_password agent_server_ip_address 1.3.6.1.2.1.1.1.0

      A string 1.3.6.1.2.1.1.1.0 é a IDO responsável pela exibição das informações do sistema. Ela retornará o resultado do uname -a no sistema remoto.

      Isso dará o seguinte resultado:

      Output

      SNMPv2-MIB::sysDescr.0 = STRING: Linux agent 4.15.0-66-generic #75-Ubuntu SMP Tue Oct 1 05:24:09 UTC 2019 x86_64

      Agora que você verificou que é possível autenticar-se ao servidor executando o daemon do SNMP, continue para criar sua conta de usuário normal.

      Passo 5 — Configurando a conta de usuário normal

      Embora tenha especificado os privilégios para a conta de usuário demo no arquivo snmpd.conf, você ainda não criou este usuário. Neste passo, você utilizará o usuário bootstrap como modelo para seu novo usuário. Você fará isso usando a ferramenta snmpusm, usada para a gestão de usuários.

      No manager server, é possível criar o usuário a partir do modelo, utilizando a ferramenta snmpusm e a seguinte sintaxe geral:

      snmpusm authentication_info agent_server_ip_address create new_user existing_user
      

      Usando o que sabe sobre os sinalizadores de autenticação que você precisa passar e aproveitando a conta de usuário que já tem (bootstrap), crie um usuário que corresponda aos privilégios do usuário que já definiu (demo).

      O comando ficará parecido com este:

      • snmpusm -u bootstrap -l authPriv -a MD5 -x DES -A temp_password -X temp_password agent_server_ip_address create demo bootstrap

      Você receberá a seguinte mensagem:

      Output

      User successfully created.

      Agora, você tem um usuário totalmente funcional chamado demo em seu agent server. No entanto, ele ainda está usando as mesmas informações de autenticação da conta bootstrap. Para aumentar a segurança, modifique a senha para uma outra. Desta vez, você utilizará a conta demo para se autenticar. Lembre-se: senhas devem ter pelo menos oito caracteres:

      • snmpusm -u demo -l authPriv -a MD5 -x DES -A temp_password -X temp_password agent_server_ip_address passwd temp_password new_password

      Você receberá a seguinte mensagem:

      Output

      SNMPv3 Key(s) successfully changed.

      Teste suas novas credenciais e senha perguntando ao agent server quanto tempo o serviço do SNMP está funcionando. Será utilizado o comando snmpget para obter um valor único do agent server.

      Desta vez,aproveite das definições extras do MIB baixadas para pedir o valor pelo nome, em vez da ID numérica IDO.

      • snmpget -u demo -l authPriv -a MD5 -x DES -A new_password -X new_password agent_server_ip_address sysUpTime.0

      Você receberá um valor que representa a última vez que o daemon remoto do SNMP foi reiniciado:

      Output

      DISMAN-EVENT-MIB::sysUpTimeInstance = Timeticks: (53309) 0:08:53.09

      Agora, você tem uma conta de usuário funcional chamada demo. No próximo passo, você simplificará o trabalho com os comandos do SNMP ao configurar o cliente.

      Passo 6 — Criando um arquivo de configuração de Cliente

      Neste ponto, você provavelmente notou que os detalhes de autenticação para todos os seus comandos do SNMP serão bastante estáticos em cada pedido. Em vez de digitá-los toda vez, é possível criar um arquivo de configuração do lado do cliente que terá as credenciais às quais você está se conectando.

      O arquivo de configuração de cliente pode ser colocado em dois locais diferentes, dependendo de como deseja compartilhá-lo.

      Caso queira compartilhar suas credenciais de login com qualquer usuário válido em sua máquina de gerenciamento, você pode colocar seus detalhes de configuração no arquivo global snmp.conf no manager server. Será necessário abrir esse arquivo com privilégios do sudo:

      • sudo nano /etc/snmp/snmp.conf

      No entanto, caso queira definir as credenciais de autenticação para apenas seu usuário, crie um diretório .snmp escondido dentro do diretório home do seu usuário no manager server e crie o arquivo lá:

      • mkdir ~/.snmp
      • nano ~/.snmp/snmp.conf

      Independentemente de sua decisão sobre onde colocar sua configuração, o conteúdo será o mesmo.

      Os comandos que você usará para autenticar estão na tabela a seguir. Na coluna da direita, é possível ver os nomes da diretiva usados para definir esses detalhes de configuração dentro do arquivo snmp.conf:

      Sinalizador de comandoDescriçãoDiretiva snmp.conf traduzida
      -u usernameO nome de usuário do SNMPv3 para se autenticar.defSecurityName username
      -l authPriv​​​​​​O nível de segurança para se autenticar.defSecurityLevel authPriv​​​
      -a MD5​​​O protocolo de autenticação que deve ser usado.defAuthType MD5​​​
      -x DESO protocolo de privacidade (criptografia) que deve ser usado.defPrivType DES​​​
      -A passphrase​​​A senha de autenticação para o nome de usuário fornecido.defAuthPassphrase passphrase​​​
      -X passphrase​​​A senha de privacidade do nome de usuário fornecido.defPrivPassphrase passphrase​​​

      Ao usar essas informações, é possível construir um arquivo snmp.conf adequado. Para este guia, ele ficará parecido com isto:

      snmp.conf

      defSecurityName demo
      defSecurityLevel authPriv
      defAuthType MD5
      defPrivType DES
      defAuthPassphrase new_password
      defPrivPassphrase new_password
      

      Quando você terminar, salve e feche o arquivo.

      Agora, é possível emitir comandos sem fornecer os detalhes de autenticação. Será necessário apenas o comando SNMP, o host e os argumentos do comando.

      Em vez de digitar:

      • snmpget -u demo -l authPriv -a MD5 -x DES -A new_password -X new_password agent_server_ip_address sysUpTime.0

      Digite:

      • snmpget agent_server_ip_address sysUpTime.0

      Como pode ver, isso reduz significativamente a quantidade de informações necessárias para se fornecer em cada pedido. A seguir, você removerá a conta bootstrap para reforçar a segurança da rede.

      Passo 7 — Removendo a conta Bootstrap

      Agora que sua conta normal está configurada corretamente, você pode remover a conta bootstrap não segura.

      Em seu agent server, abra novamente o arquivo /etc/snmp/snmpd.conf​​​ com privilégios sudo.

      • sudo nano /etc/snmp/snmpd.conf

      Encontre e deixe como comentário (ou remova) ambas as linhas adicionadas anteriormente que faziam referência ao usuário bootstrap:

      /etc/snmp/snmpd.conf

      ...
      #createUser bootstrap MD5 temp_password DES
      #rwuser bootstrap priv
      ...
      

      Salve e feche o arquivo.

      Agora, reinicie o daemon do SNMP:

      • sudo systemctl restart snmpd

      Isso cumprirá a recomendação de não ter diretivas do tipo createUser no arquivo snmpd.conf normal. Isso também removerá os privilégios desse usuário temporário.

      Caso queira remover completamente o usuário bootstrap do usmUserTable, envie este comando pelo manager server:

      • snmpusm agent_server_ip_address delete bootstrap

      Você receberá a seguinte resposta:

      Output

      User successfully deleted.

      Conclusão

      Neste ponto, você tem uma instalação de cliente-servidor totalmente configurada que consegue se comunicar com segurança usando o protocolo do SNMP. Agora, é possível adicionar daemons adicionais em outros hosts e configurar o acesso de conta em toda sua infraestrutura.

      Para estudar mais a respeito das ferramentas do SNMP e como utilizá-las para recuperar valores um a um ou em massa, e como modificar dados, utilize nosso tutorial sobre Como utilizar o conjunto de ferramentas Net-SNMP para gerenciar e monitorar servidores.



      Source link

      How To Install and Configure an SNMP Daemon and Client on Ubuntu 18.04


      The author selected the Internet Archive to receive a donation as part of the Write for DOnations program.

      Introduction

      A large part of being a system administrator is collecting accurate information about your servers and infrastructure. There are a number of tools and options for gathering and processing this type of information. Many of them are built upon a technology called SNMP.

      SNMP stands for simple network management protocol. It is a way that servers can share information about their current state, and also a channel through which an administer can modify pre-defined values. While the protocol itself is lightweight, the structure of programs that implement SNMP can quickly grow in complexity. For more information on the basics of the SNMP protocol, see our An Introduction to SNMP article.

      In this guide, you will set up the tools to communicate using SNMP. You will be using two Ubuntu 18.04 servers to demonstrate. One will contain the SNMP manager, which will talk to the agent to implement network devices. This will be called the manager server. The other server will have the SNMP agent, which will act on the orders from the manager server. This will be called the agent server. You could choose to install the agent on the manager machine as well, but keeping them separate makes it easier to demonstrate what functionality is provided by each component.

      Prerequisites

      To follow this tutorial, you will need:

      Step 1 — Installing the SNMP Daemon and Utilities

      You can begin to explore how SNMP can be implemented on a system by installing the daemon and tools on your Ubuntu servers.

      From your local machine, log into the manager server as your non-root user:

      • ssh your_username@manager_server_ip_address

      Update the package index for the APT package manager:

      Next, install the SNMP software:

      • sudo apt install snmp snmp-mibs-downloader

      The snmp package provides a collection of command line tools for issuing SNMP requests to agents. The snmp-mibs-downloader package will help to install and manage Management Information Base (MIB) files, which keep track of network objects.

      Then, open up a new terminal on your local machine and log into the agent server:

      • ssh your_username@agent_server_ip_address

      On the agent server, update the package index:

      Then, install the SNMP daemon

      Note that you do not need the snmp-mibs-downloader package, since the agent server will not be managing MIB files.

      Now that you have installed these components, you will configure your manager server.

      Step 2 — Configuring the SNMP Manager Server

      As mentioned before, most of the bulk of the work happens in the agent server, so your configuration on the manager server will be less involved. You just need to modify one file to make sure that SNMP tools can use the extra MIB data you installed.

      On your manager server, open the /etc/snmp/snmp.conf file in your text editor with sudo privileges. This tutorial will use nano:

      • sudo nano /etc/snmp/snmp.conf

      In this file, there are a few comments and a single un-commented line. To allow the manager to import the MIB files, comment out the mibs : line:

      /etc/snmp/snmp.conf

      # As the snmp packages come without MIB files due to license reasons, loading
      # of MIBs is disabled by default. If you added the MIBs you can reenable
      # loading them by commenting out the following line.
      #mibs :
      

      Save and close snmp.conf by pressing CTRL+X, followed by Y, and then ENTER if you’re using nano.

      You are now finished configuring the manager server, but you will still need to use this server to help configure your agent server, which you will do in the next step.

      Step 3 — Configuring the SNMP Agent Server

      As a true client-server system, the agent server does not have any of the external tools needed to configure its own SNMP setup. You can modify some configuration files to make some changes, but most of the changes you need to make will be done by connecting to your agent server from your management server.

      In this tutorial, you will use version 3 of the SNMP protocol. Unlike SNMPv1 and v2, in SNMPv3 each message contains security parameters that are encoded. In this step you will configure SNMPv3 authentication and access control rules.

      To get started, on your agent server, open the daemon’s configuration file with sudo privileges:

      • sudo nano /etc/snmp/snmpd.conf

      Inside, you will have to make a few changes. These will mainly be used to bootstrap your configuration so that you can manage it from your other server.

      First, you need to change the agentAddress directive. Currently, it is set to only allow connections originating from the local computer. You’ll need to comment out the current line, and uncomment the line underneath, which allows all connections.

      /etc/snmp/snmpd.conf

      #  Listen for connections from the local system only
      #agentAddress  udp:127.0.0.1:161
      #  Listen for connections on all interfaces (both IPv4 *and* IPv6)
      agentAddress udp:161,udp6:[::1]:161
      

      Note: Since allowing all connections like this is not a security best practice, it is best to make sure to lock this back down soon, after the bootstraping is complete.

      Next, you will temporarily insert a createUser line. These directives are not normally kept in this file; you will be removing it again in a moment.

      The user you are creating will be called bootstrap and will be used as a template in which to create your first actual user. The SNMP packages do this through a process of cloning the user’s properties.

      When defining a new user, you must specify the authentication type (MD5 or SHA) as well as supply a passphrase that must be at least eight characters. If you plan on using encryption for the transfer, like you will in this tutorial, you also must specify the privacy protocol (DES or AES) and optionally a privacy protocol passphrase. If no privacy protocol passphrase is supplied, the authentication passphrase will be used for the privacy protocol as well.

      Add this createUser line to the end of the file:

      /etc/snmp/snmpd.conf

      ...
      createUser bootstrap MD5 temp_password DES
      

      Now that you have a new user specified, you can set up the level of access that this user will have. In this tutorial you will set this up for your bootstrap user, and also for the new user you will be creating, called demo. You will allow them read and write access by using the rwuser directive (the alternative is rouser for read-only access).

      You will also enforce the use of encryption by specifying priv after your user. If you wanted to restrict the user to a specific part of the MIB, you could specify the highest-level object identifier (OID) that the user should have access to at the end of the line.

      For this tutorial’s purposes, both of your lines will be as follows:

      /etc/snmp/snmpd.conf

      ...
      rwuser bootstrap priv
      rwuser demo priv
      

      When you are finished making these changes, save and close the file.

      To implement these changes, restart the snmpd service on your agent server:

      • sudo systemctl restart snmpd

      The SNMP daemon will listen for connections on port :161. Configure UFW to allow connections from the manager server to this port:

      • sudo ufw allow from manager_server_ip_address to any port 161

      You can learn more about UFW in How To Set Up a Firewall with UFW on Ubuntu 18.04.

      Now that the agent server is configured, you can connect to your agent server from the manager server to verify the connection.

      Step 4 — Verifying Authentication to the Agent Server

      In this step, you will test to make sure you can connect with your bootstrap account to the agent server. Before that, however, this tutorial will talk a bit about the general structure of sending an SNMP command.

      When using the suite of tools included in the snmp package (the net-snmp software suite), there are a few patterns in the way you must call the commands. The first thing to do is authenticate with the SNMP daemon that you wish to communicate with. This usually involves supplying a few pieces of information. The common ones are as follows:

      • -v: This flag is used to specify the version of the SNMP protocol that you would like to use. This tutorial will be using v3.
      • -c: This flag is used if you are using SNMP v1 or v2-style community strings for authentication. Since you are using v3-style user-based authentication, you don’t need to do this.
      • -u: This parameter is used to specify the username that you wish to authenticate as. To read or modify anything using SNMP, you must authenticate with a known username.
      • -l: This is used to specify the security level that you are connecting with. The possible values are noAuthNoPriv for no authentication and no encryption, authNoPriv for authentication but no encryption, and authPriv for authentication and encryption. The username that you are using must be configured to operate at the security level you specify, or else the authentication will not succeed.
      • -a: This parameter is used to specify the authentication protocol that is used. The possible values are MD5 or SHA. This must match the information that was specified when the user was created.
      • -x: This parameter is used to specify the encryption protocol that is used. The possible values are DES or AES. This must match the information that was specified when the user was created. This is necessary whenever the user’s privilege specification has priv after it, making encryption mandatory.
      • -A: This is used to give the authentication passphrase that was specified when the user was created.
      • -X: This is the encryption passphrase that was specified when the user was created. If none was specified but an encryption algorithm was given, the authentication passphrase will be used. This is required when the -x parameter is given or whenever a user’s privilege specification has a priv after it, requiring encryption.

      Using this information, you can construct your commands. Given how you set up your bootstrap user, the commands you will be using with that account will look like this:

      snmp_command -u bootstrap -l authPriv -a MD5 -x DES -A temp_password -X temp_password remote_host snmp_sub_command_or_options
      

      From your manager server, test to make sure your bootstrap account is available. Type the following to display the system information for the agent server:

      • snmpget -u bootstrap -l authPriv -a MD5 -x DES -A temp_password -X temp_password agent_server_ip_address 1.3.6.1.2.1.1.1.0

      The 1.3.6.1.2.1.1.1.0 string is the OID that is responsible for displaying system information. It will return the output of uname -a on the remote system.

      This will give the following output:

      Output

      SNMPv2-MIB::sysDescr.0 = STRING: Linux agent 4.15.0-66-generic #75-Ubuntu SMP Tue Oct 1 05:24:09 UTC 2019 x86_64

      Now that you have verified that you can authenticate to the server running the SNMP daemon, you can continue on to create your regular user account.

      Step 5 — Setting Up the Regular User Account

      Although you have specified the privileges for the demo user account in the snmpd.conf file, you haven’t actually created this user yet. In this step, you are going to use the bootstrap user as a template for your new user. You will do this using the snmpusm tool, which is used for user management.

      On the manager server, you can create the user from the template using the snmpusm tool and the following general syntax:

      snmpusm authentication_info agent_server_ip_address create new_user existing_user
      

      Using what you know about the authentication flags you need to pass, and leveraging the user account you already have (bootstrap), you can make a user that fits the user privileges you have already defined (demo).

      The command will look like this:

      • snmpusm -u bootstrap -l authPriv -a MD5 -x DES -A temp_password -X temp_password agent_server_ip_address create demo bootstrap

      You will receive the following message:

      Output

      User successfully created.

      You now have a fully functioning user called demo on your agent server. However, it is still using the same authentication information as the bootstrap account. To increase security, you can change the password to something else. This time, you will use the demo account to authenticate. Remember, passwords must be at least eight characters long:

      • snmpusm -u demo -l authPriv -a MD5 -x DES -A temp_password -X temp_password agent_server_ip_address passwd temp_password new_password

      You will receive the following message back:

      Output

      SNMPv3 Key(s) successfully changed.

      You can test your new credentials and password by asking the agent server how long the SNMP service has been running. You will use the snmpget command to get a single value from the agent server.

      This time, take advantage of the extra MIB definitions you downloaded to ask for the value by name instead of the OID numeric ID.

      • snmpget -u demo -l authPriv -a MD5 -x DES -A new_password -X new_password agent_server_ip_address sysUpTime.0

      You will get back a value that represents the last time that the remote SNMP daemon was restarted:

      Output

      DISMAN-EVENT-MIB::sysUpTimeInstance = Timeticks: (53309) 0:08:53.09

      You now have a working user account named demo. In the next step, you will simplify working with SNMP commands by configuring the client.

      Step 6 — Creating a Client Configuration File

      You have probably noticed by this point that the authentication details for all of your SNMP commands will be fairly static with each request. Rather than typing these in each time, you can create a client-side configuration file that will contain the credentials you are connecting with.

      The client configuration file can be placed in two different locations depending on how wide-spread you wish to share it.

      If you want to share your login credentials with any valid user on your management machine, you can place your configuration details into the global snmp.conf file on the manager server. You would need to open that file with sudo privileges:

      • sudo nano /etc/snmp/snmp.conf

      If, however, you want to define the authentication credentials for your user alone, you can create a hidden .snmp directory within your user’s home directory on the manager server, and create the file there:

      • mkdir ~/.snmp
      • nano ~/.snmp/snmp.conf

      Regardless of your decision on where to place your configuration, the contents will be the same.

      The commands that you will be using to authenticate are in the following table. In the right-hand column, you can see the directive names used to set those configuration details within the snmp.conf file:

      Command FlagDescriptionTranslated snmp.conf directive
      -u usernameThe SNMPv3 username to authenticate as.defSecurityName username
      -l authPrivThe security level to authenticate with.defSecurityLevel authPriv
      -a MD5The authentication protocol to use.defAuthType MD5
      -x DESThe privacy (encryption) protocol to use.defPrivType DES
      -A passphraseThe authentication passphrase for the supplied username.defAuthPassphrase passphrase
      -X passphraseThe privacy passphrase from the supplied username.defPrivPassphrase passphrase

      Using this information, you can construct an appropriate snmp.conf file. For this guide, it will look like this:

      snmp.conf

      defSecurityName demo
      defSecurityLevel authPriv
      defAuthType MD5
      defPrivType DES
      defAuthPassphrase new_password
      defPrivPassphrase new_password
      

      When you are finished, save and close the file.

      Now, you can issue commands without supplying the authentication details. You will only need the SNMP command, the host, and the command arguments.

      Instead of typing:

      • snmpget -u demo -l authPriv -a MD5 -x DES -A new_password -X new_password agent_server_ip_address sysUpTime.0

      You can type:

      • snmpget agent_server_ip_address sysUpTime.0

      As you can see, this significantly reduces the amount of information you need to supply in each request. Next, you will remove the bootstrap account to tighten the network security.

      Step 7 — Removing the Bootstrap Account

      Now that your regular account is configured correctly, you can remove the insecure bootstrap account.

      On your agent server, open the /etc/snmp/snmpd.conf file again with sudo privileges.

      • sudo nano /etc/snmp/snmpd.conf

      Find and comment out (or remove) both of the lines that you previously added that reference the bootstrap user:

      /etc/snmp/snmpd.conf

      ...
      #createUser bootstrap MD5 temp_password DES
      #rwuser bootstrap priv
      ...
      

      Save and close the file.

      Now, restart the SNMP daemon:

      • sudo systemctl restart snmpd

      This will fulfill the recommendation of not having createUser directives in the normal snmpd.conf file. It will also remove privileges from that temporary user.

      If you want to completely remove the bootstrap user from the usmUserTable, you can do so by issuing this command from the manager server:

      • snmpusm agent_server_ip_address delete bootstrap

      You will receive the following response:

      Output

      User successfully deleted.

      Conclusion

      At this point, you have a fully configured client-server setup that can communicate securely using the SNMP protocol. You can now add additional daemons on other hosts and configure account access across your entire infrastructure.

      For further study, you can use our How To Use the Net-SNMP Tool Suite To Manage and Monitor Servers tutorial to learn about SNMP tools and how to use them to retrieve values one-by-one or by bulk and how to modify data.



      Source link