本文实例为大家分享了python端口扫描的实现代码,供大家参考,具体内容如下
获取本机的ip和端口号:
import socket
def get_my_ip():
try:
csock = socket.socket(socket.af_inet, socket.sock_dgram)
csock.connect((‘8.8.8.8’, 80))
(addr, port) = csock.getsockname()
csock.close()
return addr,port
except socket.error:
return “127.0.0.1”
def int_to_ip(int_ip):
return socket.inet_ntoa(struct.pack(‘i’, socket.htonl(int_ip)))
def ip_to_int(ip):
return socket.ntohl(struct.unpack(“i”, socket.inet_aton(str(ip)))[0])
(ip,port)=get_my_ip()
portscan.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
import optparse
from socket import *
from threading import *
screenlock = semaphore(value=1)
def connscan(tgthost, tgtport):
try:
connskt = socket(af_inet, sock_stream)
connskt.connect((tgthost, tgtport))
connskt.send(‘violentpython\r\n’)
results = connskt.recv(100)
screenlock.acquire()
print ‘[+] %d/tcp open’ % tgtport
print ‘[+] ‘ + str(results)
except:
screenlock.acquire()
print ‘[-] %d/tcp closed’ % tgtport
finally:
screenlock.release()
connskt.close()
def portscan(tgthost, tgtports):
try:
tgtip = gethostbyname(tgthost)
except:
print “[-] cannot resolve ‘%s’: unknown host” %tgthost
return
try:
tgtname = gethostbyaddr(tgtip)
print ‘\n[+] scan results for: ‘ + tgtname[0]
except:
print ‘\n[+] scan results for: ‘ + tgtip
setdefaulttimeout(1)
for tgtport in tgtports:
t = thread(target=connscan,args=(tgthost,int(tgtport)))
t.start()
def main():
parser = optparse.optionparser(‘usage %prog ‘+\
‘-h -p ‘)
parser.add_option(‘-h’, dest=’tgthost’, type=’string’,\
help=’specify target host’)
parser.add_option(‘-p’, dest=’tgtport’, type=’string’,\
help=’specify target port[s] separated by comma’)
(options, args) = parser.parse_args()
tgthost = options.tgthost
tgtports = str(options.tgtport).split(‘,’)
if (tgthost == none) | (tgtports[0] == none):
print parser.usage
exit(0)
portscan(tgthost, tgtports)
if __name__ == ‘__main__’:
main()
以上就是python端口扫描的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。