Contents
3.34. python实现端口扫描¶
3.34.1. 使用socket工厂函数¶
代码示例1¶
#!/usr/bin/env python
# -*- coding:utf8 -*-
# auther; 18793
# Date:2019/6/19 23:03
# filename: python实现端口扫描.py
from socket import *
def conn_scan(host, port):
conn = socket(AF_INET, SOCK_STREAM)
try:
conn.connect((host, port))
print(host, port, "is avaliable")
except Exception as e:
print(host, port, "is not avaliable")
finally:
conn.close()
def main():
host = "127.0.0.1"
for port in range(20, 5000):
conn_scan(host, port)
if __name__ == '__main__':
main()
eg
#!/usr/bin/env python
# -*- coding:utf8 -*-
# auther; 18793
# Date:2019/4/17 12:43
# filename: check_port.py
import socket
def check_server(address, port=80):
s = socket.socket()
print('Attempting to connect to %s on port %s' % (address, port))
try:
s.connect((address, port))
print('Connected to %s on port %s' % (address, port))
return True
except socket.error as e:
print('Connection to %s on port %s failed: %s' % (address, port, e))
return False
finally:
s.close()
check_server("220.181.111.37")
eg
#!/usr/bin/env python
# -*- coding:utf8 -*-
# auther; 18793
# Date:2019/6/21 10:23
# filename: socket实现端口扫描.py
import socket
import threading
import time
def testconn(host, port):
sk = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sk.settimeout(1)
try:
sk.connect((host, port))
return host + " Server is " + str(port) + " connect"
except Exception:
return host + " Server is " + str(port) + " not connect!"
sk.close()
class Test(threading.Thread):
def __init__(self):
pass
def test(self):
test_conn = testconn('127.0.0.1', 80)
print(test_conn)
def run(self):
while True:
# print time.strftime('%Y-%m-%d %H:%M:%S')
self.test()
time.sleep(1)
a = Test()
a.run()
3.34.2. 使用telnetlib标准库模块¶
代码示例2¶
#!/usr/bin/env python
# -*- coding:utf8 -*-
# auther; 18793
# Date:2019/6/19 23:10
# filename: python使用telnet模块检测端口.py
import telnetlib
def conn_scan(host, port):
t = telnetlib.Telnet()
try:
t.open(host, port, timeout=1)
print(host, port, "is avaliable")
except Exception as e:
print(host, port, "is not avaliable")
finally:
t.close()
def main():
host = "127.0.0.1"
for port in range(80, 5000):
conn_scan(host, port)
if __name__ == '__main__':
main()