端口检测
由于工作需要,需要检测服务器端口是否开启,便编写了如下代码实现(python3):
#!/usr/bin/env python
#-*-coding:utf-8-*-
import os
import multiprocessing
#检测ip那些端口是开启的
def check_port2(ip,port):
import socket
#print(args)
try:
sk = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sk.settimeout(3)
sk.connect((ip, port))
print(ip + ' ' + str(port) + ' \033[32m端口已开启!\033[0m')
except Exception as e:
print(ip + ' ' + str(port) + ' \033[31m未开启!\033[0m')
sk.close()
if __name__ == '__main__':
ip = input('请输入一个ip:')
ports = input('请输入要检测的端口号,并用逗号隔开:') #如果不输入端口 则检测以下ports中的特定端口
if ports == '':
ports = [22, 23, 3306, 9999, 443, 8080, 80, 8000, 5000,79,3389]
for port in ports:
p = multiprocessing.Process(target=check_port2, args=(ip, port))
p.start()
else:
ports = ports.split(',')
for port in ports:
check_port2(ip, int(port))