socket扫描端口
Posted python运维技术
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了socket扫描端口相关的知识,希望对你有一定的参考价值。
socket是网络编程中必要的模块,在我们日常运维中,我们也可以来实现我们一些功能,比如写一个不复杂的基于client/server架构的数据收集程序等,但今天我们不是讲如何网络编程,因为网络编程的概念太过庞大,这不是我们一篇文章能讲清楚的,希望往这方面发展的朋友我可以推荐你先把TCP/IP卷看看,建议至少要看3遍(这是我当时的的次数,如果有时间建议多看几遍),然后可以看下unix网络编程,好了,说远了,现在我们回到正题,看看如何用socket模块来扫描机器开放的端口,按惯例,先上代码:
#!/usr/bin/env python
import socket
import subprocess
import sys
from datetime import datetime
subprocess.call('clear', shell=True)
remoteServer = raw_input("Enter a remote host to scan: ")
remoteServerIP = socket.gethostbyname(remoteServer)
print "-" * 60
print "Please wait, scanning remote host", remoteServerIP
print "-" * 60
t1 = datetime.now()
try:
for port in range(1,1024):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex((remoteServerIP, port))
if result == 0:
print "Port {0}: Open".format(port)
sock.close()
except KeyboardInterrupt:
print "You pressed Ctrl+C"
sys.exit()
except socket.gaierror:
print 'Hostname could not be resolved. Exiting'
sys.exit()
except socket.error:
print "Couldn't connect to server"
sys.exit()
t2 = datetime.now()
total = t2 - t1
print 'Scanning Completed in: ', total
以上是关于socket扫描端口的主要内容,如果未能解决你的问题,请参考以下文章