基于Python socket的端口扫描程序实例代码

所有的人都想停留在那山顶,但是所有的乐趣和成长都是发生在往上爬的过程中。新的一天,早安!

本文研究的主要是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() 
print "ip=%s port=%d" %(ip,port) 

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 <target host> -p <target port>') 
 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 socket的端口扫描程序

#------------------------------------------------------------------------------- 
# Name:  PortScan 
# Purpose:  扫描网段主机的端口开放情况 
# Author:  Hao Chen 
# Python3.4 
#------------------------------------------------------------------------------- 
import socket 
def main(): 
 ip_start=input('请输入开始IP:(默认:127.0.0.1)') 
 if ip_start=='': 
  ip_start='127.0.0.1' 
  ip_end='127.0.0.1' 
 else: 
  ip_end=input('请输入结束IP:') 
  if ip_end=='': 
   ip_end='127.0.0.1' 
   
 s=input('请输入目标主机开始端口:(默认扫描常用端口)') 
 if s=='': 
  portList=[21, 22, 23, 25, 80, 135, 137, 139, 445, 1433, 1502, 3306, 3389, 8080, 9015] 
 else: 
  startport=int(s) 
  s=input('请输入目标主机结束端口:(默认:65535)') 
  if s=='': 
   endport=65535 
  else: 
   endport=int(s) 
  portList=[i for i in range(startport,endport+1)] 
  
 while 1: 
  #ip_start<ip_end 
  x1=ip_start.rfind('.');      
  x2=ip_end.rfind('.') 
  if int(ip_start[x1+1:])>int(ip_end[x2+1:]): 
   break; 
   
  #开始扫描端口 
  for port in portList: 
   print('正在扫描%s :%d' %(ip_start,port)) 
   try: 
    sk = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
    sk.settimeout(10) 
    sk.connect((ip_start,port)) 
    sk.settimeout(None) 
    print('Server %s port %d OK!' % (ip_start,port)) 
    sk.close() 
 
    #结果保存在文件中 
    f=open("IP_Port.txt",'a') 
    f.write(ip_start+' : '+str(port)+'\n') 
    f.close()     
   except Exception: 
    print('Server %s port %d is not connected!' % (ip_start,port)) 
    
  #更新ip_start 
  i=ip_start.rfind('.') 
  x=int(ip_start[i+1:])+1 
  ip_start=ip_start[:i+1]+str(x) 
   
 print('扫描完成,结果保存在IP_Port.txt文件中') 
 
if __name__ == '__main__': 
 main() 

总结

以上就是本文关于基于Python socket的端口扫描程序实例代码的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

标签: 端口扫描 Python