python socket检测端口及ping检测
python根据socket模块检测端口及vip
#!/usr/bin/env python
# -*- coding: utf8 -*- from .ping_helper import Pinger
import socket def check_port(ip, port):
'''socket检测端口连通性'''
if not port:
return True
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(3)
try:
s.connect((ip, int(port)))
s.shutdown(socket.SHUT_RDWR)
return True
except:
return False def check_vip(target_host):
'''检测vip是否可以ping通'''
pinger = Pinger(target_host=target_host)
try:
delay = pinger.ping_once()
status = True
if delay == None:
status = False
except socket.gaierror as e:
status = False
return status
#!/usr/bin/env python
# -*- coding: utf8 -*-
import socket, os,struct,select,time ICMP_ECHO_REQUEST = 8 # Platform specific
DEFAULT_TIMEOUT = 2
DEFAULT_COUNT = 4 class Pinger(object):
""" Pings to a host -- the Pythonic way""" def __init__(self, target_host, count=DEFAULT_COUNT, timeout=DEFAULT_TIMEOUT):
self.target_host = target_host
self.count = count
self.timeout = timeout def do_checksum(self, source_string):
""" Verify the packet integritity """
sum = 0
max_count = (len(source_string)/2)*2
count = 0
while count < max_count: val = source_string[count + 1]*256 + source_string[count]
sum = sum + val
sum = sum & 0xffffffff
count = count + 2 if max_count<len(source_string):
sum = sum + ord(source_string[len(source_string) - 1])
sum = sum & 0xffffffff sum = (sum >> 16) + (sum & 0xffff)
sum = sum + (sum >> 16)
answer = ~sum
answer = answer & 0xffff
answer = answer >> 8 | (answer << 8 & 0xff00)
return answer def receive_pong(self, sock, ID, timeout):
"""
Receive ping from the socket.
"""
time_remaining = timeout
while True:
start_time = time.time()
readable = select.select([sock], [], [], time_remaining)
time_spent = (time.time() - start_time)
if readable[0] == []: # Timeout
return time_received = time.time()
recv_packet, addr = sock.recvfrom(1024)
icmp_header = recv_packet[20:28]
type, code, checksum, packet_ID, sequence = struct.unpack(
"bbHHh", icmp_header
)
if packet_ID == ID:
bytes_In_double = struct.calcsize("d")
time_sent = struct.unpack("d", recv_packet[28:28 + bytes_In_double])[0]
return time_received - time_sent time_remaining = time_remaining - time_spent
if time_remaining <= 0:
return def send_ping(self, sock, ID):
"""
Send ping to the target host
"""
target_addr = socket.gethostbyname(self.target_host) my_checksum = 0 # Create a dummy heder with a 0 checksum.
header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, my_checksum, ID, 1)
bytes_In_double = struct.calcsize("d")
data = (192 - bytes_In_double) * "Q"
data = struct.pack("d", time.time()) + bytes(data.encode('utf-8')) # Get the checksum on the data and the dummy header.
my_checksum = self.do_checksum(header + data)
header = struct.pack(
"bbHHh", ICMP_ECHO_REQUEST, 0, socket.htons(my_checksum), ID, 1
)
packet = header + data
sock.sendto(packet, (target_addr, 1)) def ping_once(self):
"""
Returns the delay (in seconds) or none on timeout.
"""
icmp = socket.getprotobyname("icmp")
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
except socket.error as e:
if e.errno == 1:
# Not superuser, so operation not permitted
e.msg += "ICMP messages can only be sent from root user processes"
raise socket.error(e.msg)
except Exception as e:
print ("Exception: %s" %(e)) my_ID = os.getpid() & 0xFFFF self.send_ping(sock, my_ID)
delay = self.receive_pong(sock, my_ID, self.timeout)
sock.close()
return delay def ping(self):
"""
Run the ping process
"""
for i in range(self.count):
try:
delay = self.ping_once()
except socket.gaierror as e:
print ("Ping failed. (socket error: '%s')" % e[1])
break if delay == None:
print ("Ping failed. (timeout within %ssec.)" % self.timeout)
else:
delay = delay * 1000
print ("Get pong in %0.4fms" % delay)
注意
'''
使用使用shutdown来关闭socket的功能
SHUT_RDWR:关闭读写,即不可以使用send/write/recv/read
SHUT_RD:关闭读,即不可以使用recv/read
SHUT_WR:关闭写,即不可以使用send/write
'''
import socket s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect(("localhost",50000))
s.sendall("this is shutdown test" + "\r\n")
s.send("this is shutdown test")
s.shutdown(socket.SHUT_RDWR)
print(socket.SHUT_RDWR)
print(socket.SHUT_RD)
print(socket.SHUT_WR)
s.close()
close方法可以释放一个连接的资源,但是不是立即释放,如果想立即释放,那么在close之前使用shutdown方法
shut_rd() -------关闭接受消息通道
shut_wr()--------关闭发送消息通道
shut_rdwr()-------连个通道都关闭
使用:在close()之前加上shutdown(num)即可 [shut_rd(), shut_wr(), shut_rdwr()分别代表num 为0 1 2 ]
python socket检测端口及ping检测的更多相关文章
- python 检测端口是否被占用
前记 python中有些常用的东西,虽然小,但是非常实用.这里就做个备忘吧. 实例 检测端口是否被占用. ''' -- coding: utf-8 -- import os import sock ...
- python检测服务器是否ping通
好想在2014结束前再赶出个10篇博文来,~(>_<)~,不写博客真不是一个好兆头,至少说明对学习的欲望和对知识的研究都不是那么积极了,如果说这1天的时间我能赶出几篇精致的博文,你们信不信 ...
- Socket编程中检测端口是否被占用
一般检测一个端口是否被占用的方法是看bind是否成功,其实在Windows中有两个API可以获取到当前系统端口的占用情况(GetTcpTable/GetUdpTable),利用这两个函 ...
- 基于python检测端口是否在使用
开发中,需要开启Modbus Slave服务,但是,modbus_tk 并没有提供一个端口检测的方法,导致 modbus_tcp.TcpServer(port=502) 时候会提示端口被占用 于是需要 ...
- 手把手教你在Linux中快速检测端口的 3 个小技巧
一个执着于技术的公众号 前言 无论是要解决网络连接问题还是配置防火墙,第一件事是要检查系统实际打开了哪些端口. 本文介绍了几种快速查找 Linux 系统上哪些端口向外部开放的方法. 什么是开放端口 监 ...
- java检测端口号是否配占用
java检测端口号是否被占用的工具类: package com.frank.util; import java.io.IOException; import java.net.InetAd ...
- linux批量检测服务器能否ping通和硬盘容量状态并抛出报警的一个脚本-附详细解释
有一些linux基础,最近刚开始学shell,参考了阿良老师的一个监测服务器硬盘状态的脚本,自己进行了一些扩展,今天比较晚了,后边会把注释放上来,感觉脚本还很不完善,希望大家一起探讨一下,共同学习 2 ...
- c#检测端口是否被占用
当我们要创建一个Tcp/Ip Server connection ,我们需要一个范围在1000到65535之间的端口 . 但是本机一个端口只能一个程序监听,所以我们进行本地监听的时候需要检测端口是否被 ...
- nc检测端口是否正常服务的一个命令
最近碰到一个项目,前端用apache htttpd进行发布(80端口),通过双机负载均衡转发到后端的两个tomcat进行处理(8081和8082端口),现在需要随时监控这三个端口的情况,一旦down掉 ...
- c#检测端口是否被占用的简单实例
c#检测端口是否被占用的简单实例. 当我们要创建一个Tcp/Ip Server connection ,我们需要一个范围在1000到65535之间的端口 . 但是本机一个端口只能一个程序监听,所以我们 ...
随机推荐
- c++学习笔记(四):面向对象
目录 类 & 对象 封装 访问权限 类的构造函数&析构函数 构造函数的分类及调用 拷贝构造函数的调用时机 构造函数调用规则 深拷贝与浅拷贝 初始化列表 类对象作为类成员 静态成员 C+ ...
- Coursera self-driving2, State Estimation and Localization Week4, LIDAR
operating principles 工作原理 Velodyne 加州,Hokuyo 日本,SICK 德国 TOF 就是用发出去收到的时间差和光速算距离 basic LIDAR models (2 ...
- spark 自定义 accumulator
默认的accumulator 只是最简单的 int/float 有时候我需要一个map来作为accumulator 这样,就可以处理 <string, int>类型的计数了. 此外我还需要 ...
- verilog vscode 与AI 插件
Verilog 轻量化开发环境 背景 笔者常用的开发环境 VIAVDO, 体积巨大,自带编辑器除了linting 能用,编辑器几乎不能用,仿真界面很友好,但是速度比较慢. Sublime Text, ...
- shell脚本字符串截取方法整理
首先先声明一个变量str,下面演示以该变量为例: str='https://www.baidu.com/about.html' 1.#号截取,删除左边字符,保留右边字符 echo ${str#*//} ...
- 平面设计 – 色轮 & 配色
前言 由于之前那篇有点长, 而且色轮很重要, 所以独立写一篇呗. 参考: 一文看懂色轮 Youtube – 03 色彩 (什么是色相.纯度.明度.色环.补色?怎样配色?) Youtube – 初學繪畫 ...
- QT数据可视化框架编程实战之三维柱状图_补天云QT技术培训专家
QT数据可视化框架编程实战之三维柱状图_补天云QT技术培训专家 文章目录 QT数据可视化框架编程实战:三维柱状图可视化运行效果 主程序实现C++代码 主场景 QML代码 坐标轴QML代码 数据模型定义 ...
- QT原理与源码分析之QT反射机制原理
QT反射机制原理 本文将介绍QT反射机制创建QT对象实例的原理和流程以及源代码. 文章目录 QT反射机制创建QT对象实例 原理 流程 源码 QT反射机制创建QT对象实例 QT框架提供的基于元对象的反射 ...
- IntelliJ IDEA插入时间文本
IntelliJ IDEA插入时间文本 需求: 在使用IDEA编辑一些文本时,需要插入指定格式的当前时间文本,首先想到的是找找有没有相关的IDEA插件,看到确实有别的猿做过相关的插件,但当时找到的文章 ...
- 智和信通搭建高可靠、真稳定IT运维平台,助力能源行业高效生产
在能源企业信息化高度发展的背景下,北京智和信通有限公司推出全栈式运维管控平台--"智和网管平台",助力能源企业搭建高可靠.真稳定的IT运维平台,实现高效稳定生产. 信息化飞速发展, ...