python socket模块,nmap模块实现端口扫描器以及编码问题
socket模块实现端口扫描器
# -*- coding: utf-8 -*-
# @Author : Lan126
import optparse
from socket import *
from threading import *
screenLock = Semaphore(value=1)
def connScan(tgtHost, tgtPort):
try:
connSkt = socket(AF_INET, SOCK_STREAM)
connSkt.connect((tgtHost, tgtPort))
connSkt.send(b"Hello!Baby!!!\r\n")
results = connSkt.recv(100)
screenLock.acquire()
print("[+]%d/tcp open" % tgtPort)
print("[+] " + results.decode("utf-8"))
//得到的result为bytes转成str要用utf-8解码
except Exception as e:
screenLock.acquire()
print("[-]%d/tcp closed " % tgtPort)
print("\n"+str(e))
finally:
screenLock.release()
connSkt.close()
def portScan(tgtHost, tgtPorts):
try:
tgtIp = gethostbyname(tgtHost)
except:
print("[-] Cannot resolve '%s': Unknown host" % tgtHost)
return
try:
tgtName = gethostbyaddr(tgtIp)
print("\n[+] Scan Results for: " + tgtName[0])
except:
print("\n[+] Scan Results for: " + tgtIp)
setdefaulttimeout(1)
for tgtPort in tgtPorts:
t = Thread(target=connScan, args=(tgtHost, int(tgtPort)))
t.start()
def main():
parser = optparse.OptionParser("usage%prog" + "-H <target host> -p <target port>")
parser.add_option("-H", dest="tgtHost", type="string", help="specify target host")
parser.add_option("-p", dest="tgtPort", type="string", help="specify target port[s] separated by comma")
options, args = parser.parse_args()
tgtHost = options.tgtHost
tgtPorts = str(options.tgtPort).split(",")
if (tgtHost is None) | (tgtPorts is None):
print(parser.usage)
exit(0)
portScan(tgtHost, tgtPorts)
if __name__ == "__main__":
main()
结果图
思路
__optargs__已经没有什么好说的了,这一次的脚本中主要是利用了socket模块
我们首先创建TCP/IP套接字,这是编写进行网络通信应用程序的基础
connSkt = socket(AF_INET, SOCK_STREAM)
connSkt.connect((tgtHost, tgtPort))
利用AF_INET族,SOCK_STREAM类型的socket来实例化一个socket对象
因为选定了AF_INET族,这里的connect函数连接远端时参数为一个tuple,第一个为主机名或ip地址,第二个是端口号为整型
然后利用revc函数接受一定大小的数据,在进行如上操作的过程中,如果产生异常,则判定为端口关闭
细节
gethostbyname函数返回一个Ipv4的字符串,如果本身传入ipv4地址,则直接返回
gethostbyaddr函数返回一个triple,(hostname, aliaslist, ipaddrlist),hostname就是绑定在传入参数的hostname
这里为了能够实现正常的打印操作,必须利用信号量机制,用screenLock.acquire()进行加锁操作,如果信号量被锁上该进程继续执行,其他进程等待.finally块中释放信号量
其中Semaphore(value=1)的value为内置计数器的大小
nmap端口扫描
由于windows平台无法使用nmap模块,这里换成centos操作系统
结果
思路
和上面的实现其实大同小异不过,这里是上面的一个更高级的封装,不过这里得传ip地址和端口号,传主机名会gg
python3编码和字符串
详细讲解
主要是得知道传输或接受到网络或磁盘的的都是bytes对象,转成str要用decode从str到bytes用encode
Yosoro