Feb 03 2014

Remotely restart the SNMP daemon on Ubuntu 12.04 LTS via a Python skript

Published by at 4:43 pm under Python

It can happen that the SNMP daemon on a server crashes or stops, sometimes without leaving any hints in the system’s logfiles. If you’re running a monitoring server like WhatsUp, you can define a monitor for the SNMP service and should it be reported as down, you can define an action that launches the following Python skript to restart the daemon:

import paramiko

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy( paramiko.AutoAddPolicy())
ssh.connect('yourserver.yourdomain.net', username='pythonuser', password='password')

stdin, stdout, stderr = ssh.exec_command( "sudo service snmpd restart")


In order for this skript to work properly, the user “pythonuser” needs to be able to execute sudo commands without having to type in a password again. The used Python ssh-library, paramiko, does not easily support the use of sudo commands, so it is easier to work around the problem by allowing the user “pythonuser” to run certain commands without having to provide a password again.

In order to allow “pythonuser” to run the “service” command via “sudo” without entering an additional password, this line has to be added to the end of /etc/sudoers on the server on which you need to restart the snmp daemon:

pythonuser ALL=NOPASSWD: /usr/sbin/service

IMPORTANT: This line MUST be at the end of the file, otherwise it will NOT override any settings defined for the “sudo” or other user groups (whose members must provide passwords).

No responses yet