python扫描
一.python扫描IP地址
二.初步尝试ping命令
三.python实现代码
# 可行性探究
cmd = 'ping -n 1 192.168.2.100'
info = os.popen(cmd).read()
if '字节' in info and '时间' in info and 'TTL' in info:
print('主机存在')
else:
print('主机不存在')
def ping_host(ip):
for i in range(1, 255):
cmd = f'ping -n 1 {ip}.{i}'
info = os.popen(cmd).read()
if '字节' in info and '时间' in info and 'TTL' in info:
print(f'{ip}.{i}主机存在')
if __name__ == '__main__':
ping_host('192.168.2')
# 最终版:多线程
def ping_host(ip, start, end):
for i in range(start, end + 1):
cmd = f'ping -n 1 {ip}.{i}'
info = os.popen(cmd).read()
if '字节' in info and '时间' in info and 'TTL' in info:
print(f'{ip}.{i}主机存在')
# else:
# print(f'----{ip}.{i}主机不存在----')
# 继续优化:多线程
if __name__ == '__main__':
ip = '192.168.2'
for i in range(1, 128):
threading.Thread(target=ping_host, args=(ip, 2 * i - 1, 2 * i)).start()
四.python扫描端口
python实现扫描端口
# 可行性研究
c = socket.socket()
try:
c.connect(('192.172.0.100', 3307))
# 刚才发送成功了,但是什么提示也没有
# 连接了一个不存在的端口,抛出了无法连接的异常
except Exception:
pass
# 遍历所有的端口
c = socket.socket()
for i in range(1, 65536):
try:
c.connect(('192.172.0.100', i))
print(f'端口{i}已开放')
except Exception:
print(f'----端口{i}未开放----')
# 优化:使用常见的端口
port_list = [7, 21, 22, 23, 25, 43, 53, 67, 68, 69, 79, 80, 81, 88, 109, 110, 113, 119, 123, 135, 135,
137, 138, 139, 143, 161, 162, 179, 194, 220, 389, 443, 445, 465, 513, 520, 520, 546, 547,
554, 563, 631, 636, 991, 993, 995, 1080, 1194, 1433, 1434, 1494, 1521, 1701, 1723, 1755,
1812, 1813, 1863, 3269, 3306, 3307, 3389, 3544, 4369, 5060, 5061, 5355, 5432, 5671, 5672, 6379,
7001, 8080, 8081, 8088, 8443, 8883, 8888, 9443, 9988, 9988, 15672, 50389, 50636, 61613, 61614]
# 优化 多线程
def port_scan(port):
c = socket.socket()
try:
c.connect(('192.172.0.100', port))
print(f'端口{port}已开放')
except Exception:
# print(f'----端口{port}未开放----')
pass
if __name__ == '__main__':
for i in range(86):
threading.Thread(target=port_scan, args=(port_list[i],)).start()