python新手灰帽脚本练习---简易端口扫描

总体思路:

调用了socket模块并用connect()函数链接了相应的IP和端口号,用send()函数发送数据并用recv()函数检查响应.

 

 1 # -*- coding:utf-8 -*-
 2 
 3 __author__='Dou—wei'
 4 
 5 import socket
 6 import sys
 7 
 8 
 9 def scanner(ip,port):                                                    
10     try:
11         s = socket.socket()                                                 #创建socket
12         print "[-] Attempting to connect to " + ip + ":" + str(port)        
13         s.connect((ip,port))                                                #连接指定地址
14         s.send('try')                                                       
15         banner = s.recv(1024)                                               #获取返回信息
16         if banner:                                                          #判断返回是否为空
17             print "[+] Port " + str(port) + " open: \n" + banner
18         s.close()
19     except Exception,e:
20         print e
21 
22 def main():
23     ip = sys.argv[1]
24     port = int(sys.argv[2])
25     scanner(ip,port)
26 
27 if __name__=='__main__':
28     main()
View Code

 

效果如图:

也可以自行添加列表,通过遍历实现批量扫描:

 1 # -*- coding:utf-8 -*-
 2 
 3 __author__='Dou—wei'
 4 
 5 import socket
 6 import sys
 7 
 8 
 9 def scanner(hosts,ports):
10     for host in hosts:
11         for port in ports:                                                    
12             try:
13                 s = socket.socket()                                                 #创建socket
14                 print "[-] Attempting to connect to " + host + ":" + str(port)        
15                 s.connect((host,port))                                                #连接指定地址
16                 s.send('try')                                                       
17                 banner = s.recv(1024)                                               #获取返回信息
18                 if banner:                                                          #判断返回是否为空
19                     print "[+] Port " + str(port) + " open: \n" + banner
20                 s.close()
21             except Exception,e:
22                 print e
23 
24 def main():
25     hosts = ['127.0.0.1','192.168.1.1']
26     ports = [21,22,25,80,3389,8080]
27     scanner(hosts,ports)
28 
29 if __name__=='__main__':
30     main()
View Code

效果如图:

 

posted @ 2018-08-30 10:45  i11USi0n  阅读(301)  评论(0编辑  收藏  举报