With a python to write a simple port scanner, python environment 3.7.0, windows system
Scan a given host is open specified port
TCP connections are scanned using TCP three-way handshake to determine the host port is open. After determining the port open host, send a message to a port, the port receiving the message returned, the port then determines a running service.
When used, -H parameters may provide domain name or address of the host ip, -p / -P write ports to be scanned, a plurality of ports separated by commas
'''
@Author:yw
参考书籍:《python绝技:运用python成为顶级***》
'''
import optparse
from socket import *
import threading
threadlock = threading.Lock() #实例化threadlock对象
def Conn_scan(Host, Port):
try:
conn = socket(AF_INET,SOCK_STREAM)
conn.connect((Host, Port))
#conn.send('ywboy'.encode('utf-8')) #发送测试
#results = conn.recv(100) #接收主机返回的信息
threadlock.acquire() #加锁
print("[+]%d/tcp Open" % Port)
#print('[+]'+results.decode('utf-8'))
conn.close()
except Exception as e:
threadlock.acquire() #释放锁
print('[-]%d/Tcp Closed' % Port)
finally:
threadlock.release()
conn.close()
def Port_scan(Host, Ports):
try:
IP = gethostbyname(Host) ##获得对应主机的ip地址
except:
print("[-] Cannot resolve '%s':Unknow host" % Host)
return
try:
Name = gethostbyaddr(Host) ##获得对应主机的信息,返回主机名、主机别名列表、主机IP地址列表
print("\n[+] Scan result for:"+Name[0])
except:
print("\n[+] Scan Results for:"+IP)
setdefaulttimeout(1)
for Port in Ports:
print("Scan port:"+Port)
Conn_scan(Host, int(Port))
def main():
usage = "usage %prog -H <target Host> -p/-P <target ports>"
parse = optparse.OptionParser(usage)
parse.add_option('-H', dest='Host', type='string', help='target Host')
parse.add_option('-p','-P', dest='Ports', type='string', help='SCan Port')
(options, args) = parse.parse_args()
Host = options.Host
Ports = str(options.Ports).split(',')
if (Host==None)|(Ports==None):
print(parse.usage)
exit(0)
Port_scan(Host,Ports)
if __name__ == '__main__':
main()
The code, because I just did a port scan, so the judge commented port scanning service code