首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > perl python >

有很多ip跟端口,需要用类似与telnet的方式检测一下端口的连通性

2013-09-06 
有很多ip和端口,需要用类似与telnet的方式检测一下端口的连通性import socketimport osfile_obj open(i

有很多ip和端口,需要用类似与telnet的方式检测一下端口的连通性

import socket
import os

file_obj = open('ip.txt')   

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


for line in file_obj:
ip = line.split()[0]
p = int(line.split()[1])
try:
s.connect((ip,p))
s.close()
print ip+":"+str(p)+" open"
except:
print ip+":"+str(p)+" close"
file_obj.close()


代码如上
运行结果如下:
C:\pycode>python 1111.py
Began to detect...
127.0.0.1:8080 close
127.0.0.1:80 open
127.0.0.1:80 close
127.0.0.1:80 close
192.168.1.1:80 close

同样是127.0.0.1:80  为什么第一个可以之后就不行了呢?
[解决办法]
s.close()之后,就不能再重复用了。把 s=...放到循环体内。

import socket
import os

file_obj = open('ip.txt')   

for line in file_obj:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ip = line.split()[0]
p = int(line.split()[1])
try:
s.connect((ip,p))
s.close()
print ip+":"+str(p)+" open"
except:
print ip+":"+str(p)+" close"
file_obj.close()


热点排行