A library that monitors the life and death of other machines by pinging from Python

How to check communication with other machines with Python code

When managing the system, you may come across a case where you want to monitor the life and death of other machines with the ping command. In such a case, when using the ping command from a system made with Python, I think that it is common to call the OS ping command using subprocess. However, in this case, since external commands are used, there are problems that it depends on the external environment and that fine control is difficult.

Therefore, this time I will introduce a library for life and death monitoring by socket so that it will be completed in Python.

Life and death monitoring using Pings

pings is a library for sending pings in Python. As mentioned above, the ICMP packet used for ping can be sent using socket without using the subprocess command.

** Note **: pings must be run as root / admin user.

Installation

It can be installed via pip.

pip install pings

How to use

If you want to monitor the life and death status of the target, do as follows. * Be sure to run it as ** root user / admin user ** at runtime.

--Initialize the Ping object --Specify the monitoring target in the argument of the ping () method --This method pings the target and returns a response object as a return value. --Communication result is stored in ʻis_reached ()` of this object

Specifically, the code looks like this:

.python


import pings

p = pings.Ping() #Ping object creation
res = p.ping("google.com")  #Monitor google

if res.is_reached():
  #I was able to connect to the monitoring target
  do_something()
else:
  #Could not connect to the monitored target
  do_something()

You can use the response object obtained as the return value of the ping method to help monitor the network status.

res = p.ping("google.com")
res.print_messages()  #Message is displayed

Example of execution result:

PING google.com (172.217.27.174): 55 data bytes
47 bytes from 172.217.27.174: icmp_seq=0 ttl=49 time=32.333 ms
--- google.com ping statistics ---
1 packets transmitted, 1 packets received, 0.0% packet loss
round-trip min/avg/max = 32.333/32.333/32.333 ms

Finer settings

I want to monitor the life and death of multiple targets

To monitor the life and death of multiple machines, do as follows.

.python


import pings

#IP address of life and death monitoring machine
hosts = ["192.168.0.1", "192.168.0.2", "192.168.0.3"]

p = pings.Ping()

#Extract the IP addresses of the machines one by one and execute the ping command
for h in hosts:
  res = p.ping(h)
  if not res.is_reached():
    #What to do if you cannot connect
    do_something()

I want to ping multiple times

With the default settings, you can ping only once, so use the times option if you want to send multiple times.

.python


import pings

p = pings.Ping()
res = p.ping("google.com", times=3)  #Monitor google,Ping 3 times
res.print_messages()

Example of execution result:

PING google.com (172.217.27.174): 55 data bytes
47 bytes from 172.217.27.174: icmp_seq=0 ttl=49 time=32.333 ms
--- google.com ping statistics ---
1 packets transmitted, 1 packets received, 0.0% packet loss
round-trip min/avg/max = 32.333/32.333/32.333 ms

I want to output the result to the standard output

By specifying the quiet option to False when initializing the Ping class, the ping result will be displayed on standard output during execution.

.python


import pings

p = pings.Ping(quiet=False)
res = p.ping("google.com")  #Monitor google

Example of execution result:

PING google.com (172.217.27.174): 55 data bytes
47 bytes from 172.217.27.174: icmp_seq=0 ttl=49 time=32.333 ms
--- google.com ping statistics ---
1 packets transmitted, 1 packets received, 0.0% packet loss
round-trip min/avg/max = 32.333/32.333/32.333 ms

in conclusion

Due to insufficient testing, there may be problems such as not working or not working well in some environments. If you want to use it, please be aware of it before using it.

If you have any problems or comments, please write them in the comments section or in the issue on Github.

reference

http://edo.blog.jp/archives/1790336.html

Recommended Posts

A library that monitors the life and death of other machines by pinging from Python
From a book that makes the programmer's way of thinking interesting (Python)
A discussion of the strengths and weaknesses of Python
[Python] A program that calculates the number of updates of the highest and lowest records
[Python] A program that counts the number of valleys
Python points from the perspective of a C programmer
[Python] A program that compares the positions of kangaroos.
A python script that gets the number of jobs for a specified condition from indeed.com
A python client application that downloads and deletes files from S3 by specifying a bucket
[Python] Representing the number of complaints from life insurance companies in a bar graph
Different from the import type of python. from A import B meaning
An example of a mechanism that returns a prediction by HTTP from the result of machine learning
Python: Create a dictionary from a list of keys and values
A Python script that allows you to check the status of the server from your browser
A Python script that compares the contents of two directories
[Python] A program to find the number of apples and oranges that can be harvested
I made a Line bot that guesses the gender and age of a person from an image
Find the white Christmas rate by prefecture with Python and map it to a map of Japan
[Python] A program that compares each element of list one by one and wins or loses. zip ()
Save the result of the life game as a gif with python
A formula that simply calculates the age from the date of birth
A story that struggled to handle the Python package of PocketSphinx
Read the standard output of a subprocess line by line in Python
From a book that programmers can learn (Python): Find the mode
From a book that programmers can learn ... (Python): Review of arrays
[Python] Get the update date of a news article from HTML
A function that measures the processing time of a method in python
Verification of the theory that "Python and Swift are quite similar"
[python] A note that started to understand the behavior of matplotlib.pyplot
The story of making a module that skips mail with python
[Python] A program that rotates the contents of the list to the left
The story of Python and the story of NaN
Existence from the viewpoint of Python
This and that of python properties
Set up a dummy SMTP server in Python and check the operation of sending from Action Mailer
[Python] I analyzed the diary of a first-year member of society and made a positive / negative judgment on the life of a member of society.
Extension of Python by C or C ++ (when there are multiple arguments, when passing a list from the Python side)
Calculate the shortest route of a graph with Dijkstra's algorithm and Python
[Python] A program that calculates the number of socks to be paired
Extract lines that match the conditions from a text file with python
Enum types that enter the standard library from Python 3.4 are still useful
I tried to verify and analyze the acceleration of Python by Cython
A note about the functions of the Linux standard library that handles time
Find out the name of the method that called it from the method that is python
Code reading of faker, a library that generates test data in Python
[Python] Note: A self-made function that finds the area of the normal distribution
This and that of the inclusion notation.
Learning notes from the beginning of Python 1
Connect a lot of Python or and and
Article that can be a human resource who understands and masters the mechanism of API (with Python code)
[python] [meta] Is the type of python a type?
Pandas of the beginner, by the beginner, for the beginner [Python]
[Python] A function that aligns the width by inserting a space in text that has both full-width and half-width characters.
The story of blackjack A processing (python)
Learning notes from the beginning of Python 2
[Python] A program that rounds the score
Try to find the probability that it is a multiple of 3 and not a multiple of 5 when one is removed from a card with natural numbers 1 to 100 using Ruby and Python.
Make the library created by Eigen in C ++ available from Python with Boost.Numpy.
The story of making a box that interconnects Pepper's AL Memory and MQTT
Python --Read data from a numeric data file and find the multiple regression line.
A Python script that reads a SQL file, executes BigQuery and saves the csv