自制最简单的端口扫描器

时间:2024-03-12 10:25:59

最近刚好想给某钟情的公众号投文章,将自己写的东西贴出来,以备不时之需。

听人说python是最简单高效智能的编程语言,所以最近在自学python编程,刚好接触到网络编程这一块儿,就自己做了个端口扫描器,环境python3,工具pycharm。附上源码,希望有兴趣的同志们可以来和我交流:

这是程序运行效果:

 

 

 

端口扫描器很简单,只是实现了最简单的效果,很适合新手练手。这儿由于没有引进线程,所以端口范围取得很小,在100~200之间,而且也是单个ip的扫描,下一步将引进线程以及增加扫描特定ip段的扫描器,谢谢大家!

下面是源码:

 1 # -*- coding: utf-8 -*-
 2 
 3 # Form implementation generated from reading ui file \'portscan.ui\'
 4 #
 5 # Created by: PyQt5 UI code generator 5.10.1
 6 #
 7 # WARNING! All changes made in this file will be lost!
 8 
 9 from PyQt5 import QtCore,QtWidgets
10 import socket
11 import sys
12 
13 
14 class Ui_Dialog(object):
15     def setupUi(self, Dialog):
16         Dialog.setObjectName("Dialog")
17         Dialog.resize(400, 300)
18         self.lineEdit_ip = QtWidgets.QLineEdit(Dialog)
19         self.lineEdit_ip.setGeometry(QtCore.QRect(40, 30, 151, 20))
20         self.lineEdit_ip.setObjectName("lineEdit_ip")
21         self.tb_ip = QtWidgets.QTextBrowser(Dialog)
22         self.tb_ip.setGeometry(QtCore.QRect(30, 80, 351, 192))
23         self.tb_ip.setObjectName("tb_ip")
24         self.bt_ok = QtWidgets.QPushButton(Dialog)
25         self.bt_ok.setGeometry(QtCore.QRect(210, 30, 75, 23))
26         self.bt_ok.setObjectName("bt_ok")
27         self.bt_cancel = QtWidgets.QPushButton(Dialog)
28         self.bt_cancel.setGeometry(QtCore.QRect(300, 30, 75, 23))
29         self.bt_cancel.setObjectName("bt_cancel")
30         self.retranslateUi(Dialog)
31         QtCore.QMetaObject.connectSlotsByName(Dialog)
32 
33     def retranslateUi(self, Dialog):
34         _translate = QtCore.QCoreApplication.translate
35         Dialog.setWindowTitle(_translate("Dialog", "端口扫描器"))
36         self.bt_ok.setText(_translate("Dialog", "OK"))
37         self.bt_ok.clicked.connect(self.start)
38         self.bt_cancel.setText(_translate("Dialog", "Cancel"))
39         self.bt_cancel.clicked.connect(self.stop)
40 
41     def portscanner(self, host, port):
42         try:
43             s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
44             s.connect((host, port))
45             self.tb_ip.append("^V^老大,这些端口开放,请笑纳! %d " % port)
46             s.close()
47         except:
48             pass
49 
50     def start(self):
51         ip = self.lineEdit_ip.text()

52         socket.setdefaulttimeout(0.1)
53         for p in range(100, 200):
54             self.portscanner(ip,p)
55         self.tb_ip.append("扫描结束,老大")
56 
57     def stop(self):
58         sys.exit()
59 
60 if __name__ == "__main__":
61     app = QtWidgets.QApplication(sys.argv)
62     form = QtWidgets.QDialog()
63     ui = Ui_Dialog()
64     ui.setupUi(form)
65     form.show()
66     sys.exit(app.exec_())