使用Python测试Ping主机IP和某端口是否开放的实例
使用Python方法
比用各种命令方便,可以设置超时时间,到底通不通,端口是否开放一眼能看出来。
命令和返回
完整权限,可以ping通,端口开放,结果如下:
无root权限(省略了ping),端口开放,结果如下:
完整权限,可以ping通,远端端口关闭,结果如下:
完整权限,可以ping通,本地端口关闭,结果如下:
完整权限,不能ping通(端口自然也无法访问),结果如下:
pnp.py代码
#!/usr/bin/python
#namepnp.py
#pingandport
#coding:utf-8
importos,sys,socket,struct,select,time
ICMP_ECHO_REQUEST=8#SeemstobethesameonSolaris.
socket.setdefaulttimeout(4)
#firstargument
host=sys.argv[1]
#secondargument
port=int(sys.argv[2])
#sockettryconnect
defPortOpen(ip,port):
print('\033[1m*Port\033[0m%s:%d'%(ip,port)),
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
try:
s.connect((ip,port))
s.shutdown(2)
print('\033[1;32m....isOK.\033[0m')
returnTrue
exceptsocket.timeout:
print('\033[1;33m....isdownornetworktimeout!!!\033[0m')
returnFalse
except:
print('\033[1;31m....isdown!!!\033[0m')
returnFalse
defchecksum(source_string):
"""
I'mnottooconfidentthatthisisrightbuttestingseems
tosuggestthatitgivesthesameanswersasin_cksuminping.c
"""
sum=0
countTo=(len(source_string)/2)*2
count=0
whilecount>16)+(sum&0xffff)
sum=sum+(sum>>16)
answer=~sum
answer=answer&0xffff
#Swapbytes.BuggermeifIknowwhy.
answer=answer>>8|(answer<<8&0xff00)
returnanswer
defreceive_one_ping(my_socket,ID,timeout):
"""
receivethepingfromthesocket.
"""
timeLeft=timeout
whileTrue:
startedSelect=time.time()
whatReady=select.select([my_socket],[],[],timeLeft)
howLongInSelect=(time.time()-startedSelect)
ifwhatReady[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
)
ifpacketID==ID:
bytesInDouble=struct.calcsize("d")
timeSent=struct.unpack("d",recPacket[28:28+bytesInDouble])[0]
returntimeReceived-timeSent
timeLeft=timeLeft-howLongInSelect
iftimeLeft<=0:
return
defsend_one_ping(my_socket,dest_addr,ID):
"""
Sendonepingtothegiven>dest_addr<.
"""
dest_addr=socket.gethostbyname(dest_addr)
#Headeristype(8),code(8),checksum(16),id(16),sequence(16)
my_checksum=0
#Makeadummyhederwitha0checksum.
header=struct.pack("bbHHh",ICMP_ECHO_REQUEST,0,my_checksum,ID,1)
#a1=struct.unpack("bbHHh",header)#mytest
bytesInDouble=struct.calcsize("d")
data=(192-bytesInDouble)*"Q"
data=struct.pack("d",time.time())+data
#Calculatethechecksumonthedataandthedummyheader.
my_checksum=checksum(header+data)
#Nowthatwehavetherightchecksum,weputthatin.It'sjusteasier
#tomakeupanewheaderthantostuffitintothedummy.
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'tknowaboutthe1
defdo_one(dest_addr,timeout):
"""
Returnseitherthedelay(inseconds)ornoneontimeout.
"""
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()
exceptsocket.error,(errno,msg):
iferrno==1:
#Operationnotpermitted
msg=msg+(
"-notroot."
)
raisesocket.error(msg)
#raise#raisetheoriginalerror
returndelay
defverbose_ping(dest_addr,timeout=2,count=100):
"""
Send>countdest_addrtimeout
使用命令方法
使用命令ping就不说了,端口可以用下面的命令。
当时目前telnet基本不用,可能没有telnet客户端了。
测试通常连接不上会等很久,端口连上了也需要通过反馈内容自行判断。
telnet
telnetipport
$telnet192.168.234.1
Trying192.168.234.1...
Connectedto192.168.234.1.
Escapecharacteris'^]'.
......
wget
wgetip:port
$wget192.168.234.1:21
--2019-03-2215:42:27--http://192.168.234.1:21/
正在连接192.168.234.1:21...已连接。
已发出HTTP请求,正在等待回应...200没有HTTP头,尝试HTTP/0.9
长度:未指定
正在保存至:“index.html”
......
SSH
ssh-vip-pport
$ssh-v192.168.234.1-p21
OpenSSH_7.4p1,OpenSSL1.0.2k-fips26Jan2017
debug1:Readingconfigurationdata/etc/ssh/ssh_config
debug1:/etc/ssh/ssh_configline58:Applyingoptionsfor*
debug1:Connectingto192.168.234.1[192.168.234.1]port21.
debug1:Connectionestablished.
......
curl
culrip:port
$curl192.168.234.1:21
220Serv-UFTPServerv15.1ready...
530Notloggedin.
......
以上这篇使用Python测试Ping主机IP和某端口是否开放的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。