python判断ip能否ping通_使用Python测试Ping主机IP和某端口是否开放的实例

使用Python方法

比用各种命令方便,可以设置超时时间,到底通不通,端口是否开放一眼能看出来。

命令和返回

完整权限,可以ping通,端口开放,结果如下:

无root权限(省略了ping),端口开放,结果如下:

完整权限,可以ping通,远端端口关闭,结果如下:

完整权限,可以ping通,本地端口关闭,结果如下:

完整权限,不能ping通(端口自然也无法访问),结果如下:

pnp.py代码

#!/usr/bin/python

#name pnp.py

#ping and port

#coding:utf-8

import os, sys, socket, struct, select, time

ICMP_ECHO_REQUEST = 8 # Seems to be the same on Solaris.

socket.setdefaulttimeout(4)

#first argument

host=sys.argv[1]

#second argument

port=int(sys.argv[2])

#socket try connect

def PortOpen(ip,port):

print( " 33[1m*Port 33[0m %s:%d" %(ip,port)),

s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)

try:

s.connect((ip,port))

s.shutdown(2)

print( " 33[1;32m.... is OK. 33[0m" )

return True

except socket.timeout:

print( " 33[1;33m.... is down or network time out!!! 33[0m" )

return False

except:

print( " 33[1;31m.... is down!!! 33[0m" )

return False

def checksum(source_string):

"""

I"m not too confident that this is right but testing seems

to suggest that it gives the same answers as in_cksum in ping.c

"""

sum = 0

countTo = (len(source_string)/2)*2

count = 0

while count

thisVal = ord(source_string[count + 1])*256 + ord(source_string[count])

sum = sum + thisVal

sum = sum & 0xffffffff # Necessary?

count = count + 2

if countTo

sum = sum + ord(source_string[len(source_string) - 1])

sum = sum & 0xffffffff # Necessary?

sum = (sum >> 16) + (sum & 0xffff)

sum = sum + (sum >> 16)

answer = ~sum

answer = answer & 0xffff

# Swap bytes. Bugger me if I know why.

answer = answer >> 8 | (answer << 8 & 0xff00)

return answer

def receive_one_ping(my_socket, ID, timeout):

"""

receive the ping from the socket.

"""

timeLeft = timeout

while True:

startedSelect = time.time()

whatReady = select.select([my_socket], [], [], timeLeft)

howLongInSelect = (time.time() - startedSelect)

if whatReady[0] == []: # Timeout

return

timeReceived = time.time()

recPacket, addr = my_socket.recvfrom(1024)

icmpHeader = recPacket[20:28]

type, code, checksum, packetID, sequence = struct.unpack(

"bbHHh", icmpHeader

)

if packetID == ID:

bytesInDouble = struct.calcsize("d")

timeSent = struct.unpack("d", recPacket[28:28 + bytesInDouble])[0]

return timeReceived - timeSent

timeLeft = timeLeft - howLongInSelect

if timeLeft <= 0:

return

def send_one_ping(my_socket, dest_addr, ID):

"""

Send one ping to the given >dest_addr<.>

"""

dest_addr = socket.gethostbyname(dest_addr)

# Header is type (8), code (8), checksum (16), id (16), sequence (16)

my_checksum = 0

# Make a dummy heder with a 0 checksum.

header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, my_checksum, ID, 1)

#a1 = struct.unpack("bbHHh",header) #my test

bytesInDouble = struct.calcsize("d")

data = (192 - bytesInDouble) * "Q"

data = struct.pack("d", time.time()) + data

# Calculate the checksum on the data and the dummy header.

my_checksum = checksum(header + data)

# Now that we have the right checksum, we put that in. It"s just easier

# to make up a new header than to stuff it into the dummy.

header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, socket.htons(my_checksum), ID, 1)

packet = header + data

my_socket.sendto(packet, (dest_addr, 1)) # Don"t know about the 1

def do_one(dest_addr, timeout):

"""

Returns either the delay (in seconds) or none on timeout.

"""

delay=None

icmp = socket.getprotobyname("icmp")

try:

my_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)

my_ID = os.getpid() & 0xFFFF

send_one_ping(my_socket, dest_addr, my_ID)

delay = receive_one_ping(my_socket, my_ID, timeout)

my_socket.close()

except socket.error, (errno, msg):

if errno == 1:

# Operation not permitted

msg = msg + (

" - not root."

)

raise socket.error(msg)

#raise # raise the original error

return delay

def verbose_ping(dest_addr, timeout = 2, count = 100):

"""

Send >count< ping to >dest_addr< with the given >timeout< and display

the result.

"""

for i in xrange(count):

print " 33[1m*Ping 33[0m %s ..." % dest_addr,

try:

delay = do_one(dest_addr, timeout)

except socket.error, e:

print " 33[1;31m... failed. (%s)" % e

break

if delay == None:

print " 33[1;31m... failed. (timeout within %ssec.) 33[0m" % timeout

else:

delay = delay * 1000

print " 33[1;32m... get ping in %0.4fms 33[0m" % delay

if __name__ == "__main__":

if os.geteuid() == 0:

verbose_ping(host,2,3)

else:

print " 33[1m*Ping 33[0m test must be sudo or root..."

PortOpen(host,port)

print( "Job finished.")

使用命令方法

使用命令ping就不说了,端口可以用下面的命令。

当时目前telnet基本不用,可能没有telnet客户端了。

测试通常连接不上会等很久,端口连上了也需要通过反馈内容自行判断。

telnet

telnet ip port

$telnet 192.168.234.1

Trying 192.168.234.1...

Connected to 192.168.234.1.

Escape character is "^]".

......

wget

wget ip:port

$wget 192.168.234.1:21

--2019-03-22 15:42:27-- http://192.168.234.1:21/

正在连接 192.168.234.1:21... 已连接。

已发出 HTTP 请求,正在等待回应... 200 没有 HTTP 头,尝试 HTTP/0.9

长度:未指定

正在保存至: “index.html”

......

SSH

ssh -v ip -p port

$ssh -v 192.168.234.1 -p 21

OpenSSH_7.4p1, OpenSSL 1.0.2k-fips 26 Jan 2017

debug1: Reading configuration data /etc/ssh/ssh_config

debug1: /etc/ssh/ssh_config line 58: Applying options for *

debug1: Connecting to 192.168.234.1 [192.168.234.1] port 21.

debug1: Connection established.

......

curl

culr ip:port

$curl 192.168.234.1:21

220 Serv-U FTP Server v15.1 ready...

530 Not logged in.

......

以上这篇使用Python测试Ping主机IP和某端口是否开放的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持云海天教程。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/409876.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

python实现抓取网页上的内容并发送到邮箱

要达到的目的&#xff1a;从特定网页中抓取信息&#xff0c;排版后发送到邮箱中 关键点&#xff1a;下载网页&#xff0c;从网页里抓取出需要的信息HTML排版发送到指定邮箱 实现&#xff1a;1.python下载网页直接用库函数就可以实现from urllib import urlretrievefrom urllib …

Thinkphp 配置不用输入index.php

版权声明&#xff1a;本文为博主原创文章&#xff0c;遵循 CC 4.0 BY-SA 版权协议&#xff0c;转载请附上原文出处链接和本声明。 本文链接&#xff1a;https://blog.csdn.net/u011186019/article/details/78495461由&#xff1a;http://127.0.0.1/thinkphp/index.php/index/in…

ue4导入倾斜摄影_倾斜摄影建模干货|还怕搞不定CC空三?这里只要5分钟……

关注公众号"三维前沿"&#xff0c;持续获取更多操作技巧干货&#xff01;01Q&#xff1a;空三刚开始就失败&#xff1f;A&#xff1a;考虑以下4种情况&#xff1a;考虑ContextCapture Engine 是否打开&#xff0c;尝试关闭后重新打开&#xff1b;考虑相片数量是否过多…

[html] 如何禁止移动端的左右划动手势?

[html] 如何禁止移动端的左右划动手势&#xff1f; html{touch-action:none;touch-action:pan-y;}个人简介 我是歌谣&#xff0c;欢迎和大家一起交流前后端知识。放弃很容易&#xff0c; 但坚持一定很酷。欢迎大家一起讨论 主目录 与歌谣一起通关前端面试题

python自增_python mysql自增字段AUTO_INCREMENT值的修改方式

在之前得文章中我们说过&#xff0c;如果使用delete对数据库中得表进行删除&#xff0c;那么只是把记录删除掉&#xff0c;并且id的值还会保持上次的状态。 即删除之前如果有四条数据&#xff0c;删除之后&#xff0c;再添加新的数据&#xff0c;id怎会从5开始。 但是我们显示想…

Python工具

1. sourcetree https://www.cnblogs.com/hoobey/p/7100593.html 2.pycharm 3. anaconda 转载于:https://www.cnblogs.com/ericazy/p/11498959.html

graphpad两组t检验_GraphPad prism -- t检验操作步骤解析~

ZSCIt检验&#xff0c;主要用于样本含量较小(例如 n<30)&#xff0c;总体标准差 σ 未知的正态分布资料&#xff0c;其中又将其分为了配对t检验和成组t检验&#xff0c;那如何利用GraphPad prism进行t检验呢&#xff1f;一、原理及意义配对t检验&#xff1a;又称配对样本均数…

[html] 在两个iframe之间传递参数的方法有哪些?

[html] 在两个iframe之间传递参数的方法有哪些&#xff1f; 通过postMessage与父级通过&#xff0c;父级传递消息通过websocket通信如果是同一个域名下可用stroage&#xff0c;监听storageChange事件通信通过web worker也可通信个人简介 我是歌谣&#xff0c;欢迎和大家一起交…

Java官方操纵byte数组的方式

java官方提供了一种操作字节数组的方法——内存流&#xff08;字节数组流&#xff09;ByteArrayInputStream、ByteArrayOutputStream ByteArrayOutputStream——byte数组合并 /*** 将所有的字节数组全部写入内存中&#xff0c;之后将其转化为字节数组*/public static void main…

python js返回 json_[python爬虫]把js转化成json

有一个优秀的库可以使用————demjson目标链接请求上面链接&#xff0c;会得到如下图的一个js文件我们需要把这个js文件转成为dict&#xff0c;方便提取其中需要的字段(这在爬虫任务中非常常见)失败的方法传统方法通常转js文件为dict的过程&#xff1a;1.先通过切片掐头去尾&…

springboot security 权限不足_springBoot整合springSecurity(零一)

整体结构》》》1&#xff0c;springboot2.0整合springSecurity5.1.12&#xff0c;mysql--->>InnoDB3&#xff0c;持久层我用的是用MybatiysPlus(这里就不写关于这个的了,基本是查)4&#xff0c;web服务不是jar服务5&#xff0c;数据库表》账户表/角色表/权限表/账户角色关…

聊聊PowerJob的OmsLogHandler

序 本文主要研究一下PowerJob的OmsLogHandler OmsLogHandler tech/powerjob/worker/background/OmsLogHandler.java Slf4j public class OmsLogHandler {private final String workerAddress;private final Transporter transporter;private final ServerDiscoveryService …

[html] 为什么移动端页面的设计稿一般是750px/640px呢?

[html] 为什么移动端页面的设计稿一般是750px/640px呢&#xff1f; 750px 代表iphone6或inphone6s 设备的像素(宽) 640px 代表inpone3Gs&#xff0c;inpone4/4s iphone5系列 设备的像素(宽) 其他手机大多数时这两种规格 750px/640px 代表的逻辑像素是 375px/320px&#xff0c;…

m文件中函数的执行顺序

当进行多个GUI协同工作时&#xff0c;要用到uiwait和uiresume函数。此时&#xff0c;理解函数的执行顺序此时是很关键的。 首先理解uiwait和uiresume函数的作用。 uiwait函数&#xff1a;阻塞m文件的执行&#xff0c;直到uiresume解除这种阻塞&#xff1b; uiresume函数&#x…

Java从string数组创建临时文件

//从string数组创建临时文件 private static File createSampleFile(String[] strs) throws IOException {File file File.createTempFile("aws-java-sdk-", ".txt");file.deleteOnExit();Writer writer new OutputStreamWriter(new FileOutputStream(fi…

关刀机器人_小学机器人活动总结

页眉内容开展青少年机器人创新实践活动情况个人总结为进一步推动我校机器人活动的普及与发展&#xff0c;培养学生对科技制作的兴趣&#xff0c;促进学生整体素质的提高&#xff0c;同时培养学生动手实践的能力&#xff0c;我校于2016年3月开展了机器人创新实践活动。在学校领导…

[html] iframe可以使用父页面中的资源吗(如:css、js等)?

[html] iframe可以使用父页面中的资源吗&#xff08;如&#xff1a;css、js等&#xff09;&#xff1f; iframe 属于一个单独的文档不能直接使用父页面的资源&#xff0c;css的层叠不会影响iframeiframe如果和父页面同域则可以在iframe中使用parent对象来使用父页的js对象个人简…

error LNK2001:unresolved external symbol __imp__@ 解决方法

我在程序Lan中使用了winsock函数&#xff0c;出现如下错误&#xff1a;Lan.obj&#xff1a;error LNK2001: unresolved external symbol __imp__listen8 Lan.obj : error LNK2001: unresolved external symbol __imp__bind12 Lan.obj : error LN…

[html] 怎么去除img之间存在的间隔缝隙?

[html] 怎么去除img之间存在的间隔缝隙&#xff1f; 1.修改display:block/flex&#xff0c; 2.父级设置font-size:0个人简介 我是歌谣&#xff0c;欢迎和大家一起交流前后端知识。放弃很容易&#xff0c; 但坚持一定很酷。欢迎大家一起讨论 主目录 与歌谣一起通关前端面试题…

zabbix基础之环境搭建

zabbix入门 环境部署 安装mysql #安装MySQL&#xff0c;官方的MySQL的repo源地址&#xff1a;http://repo.mysql.com/ #选择指定的MySQL版本&#xff0c;我这里选mysql5.7的版本,复制对应版本的链接地址。 wget http://repo.mysql.com/mysql57-community-release-el7-10.noarch…