def scan():
print "[*] Starting Scan"
nm = nmap.PortScanner()
if dns is not None:
print "[*] Performing DNS lookups using DNS server: "+dns
nm.scan(hosts=rhosts, arguments=('-sL -R --dns-server '+dns))
else:
print "[*] Performing DNS lookups using System DNS"
nm.scan(hosts=rhosts, arguments='-sL -R')
for host in nm.all_hosts():
results.append(nm[host].hostname().lower()+","+host)
print "[*] Scan Complete"
python类PortScanner()的实例源码
def scan(self, hosts, options):
import nmap
self.nm = nmap.PortScanner()
if len(options) < 2:
options = '--script nbstat.nse -O -Pn -sV -T3'
self.nm.scan(hosts, arguments=options)
#----------------------------#
# Name: out_csv
# Desc: Returns nmap results in csv string
# Input: None
# Output: Csv string containing all scan data
#----------------------------#
def nmapScan(tgtHost, tgtPort):
nmScan = nmap.PortScanner()
nmScan.scan(tgtHost, tgtPort)
state = nmScan[tgtHost]['tcp'][int(tgtPort)]['state']
print ('[*] ' + tgtHost + " tcp/" + tgtPort + " " + state)
def nmap_ping_scan(network_prefix):
nm = nmap.PortScanner()
ping_scan_raw_result = nm.scan(hosts=network_prefix, arguments='-v -n -sn')
host_list = []
for IP in ping_scan_raw_result['scan']:
if ping_scan_raw_result['scan'][IP]['status']['state'] == 'up':
host_list.append(ping_scan_raw_result['scan'][IP]['addresses']['ipv4'])
#print( '%-20s %5s' % (ping_scan_raw_result['scan'][IP]['addresses']['ipv4'],'is UP'))
return host_list
def nmap_A_scan(network_prefix):
nm = nmap.PortScanner()
scan_raw_result = nm.scan(hosts=network_prefix, arguments='-v -n -A')
os_dict = {}
for host in scan_raw_result['scan']:
if scan_raw_result['scan'][host]['status']['state'] == 'up':
for os in scan_raw_result['scan'][host]['osmatch']:
os_dict[scan_raw_result['scan'][host]['addresses']['ipv4']] = re.split(',|or', os['name'])
for x,y in os_dict.items():
y = [i.strip() for i in y]
newy = []
for z in y:
if z != '':
newy.append(z)
os_dict[x] = newy
return os_dict
def nm_scan(ip):
nm = nmap.PortScanner()
nm.scan(ip, '0-65535')
for host in nm.all_hosts():
print('----------------------------------------------------')
print('Host : %s (%s)' % (host, nm[host].hostname()), 'State : %s' % nm[host].state())
for proto in nm[host].all_protocols():
lport = sorted(nm[host][proto].keys())
for port in lport:
print('port : %s\tservice : %s' % (port, nm[host][proto][port]['product']))
def __init__(self):
self.parseconfig = ParseConfig()
self.nm = nmap.PortScanner()
self.up_targets_dict = self.parseconfig.up_targets_dict
03_06_find_network_interface_status.py 文件源码
项目:011_python_network_programming_cookbook_demo
作者: jerry-0824
项目源码
文件源码
阅读 19
收藏 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('256s', ifname[:15])
)[20:24])
nm = nmap.PortScanner()
nm.scan(ip_address, SAMPLE_PORTS)
return nm[ip_address].state()
def __init__(self, domains, id=''):
self.domains = domains
self.ips = []
self.id = id
self.nm = nmap.PortScanner()
def postAS(hostslist):
hosts = [host for host, x in hostslist.items()]
macs = [mac for x, mac in hostslist.items()]
try:
nm = nmap.PortScanner()
except Exception, ex:
try:
print "["+Fore.RED+"-"+Style.RESET_ALL+"] Exception('%s') occured\n\t%s-> Errno : %d\n\t-> Error : %s"%(type(ex).__name__,Style.DIM,ex.args[0],ex.args[1])
except:
print "["+Fore.RED+"-"+Style.RESET_ALL+"] %s"%(str(ex))
sys.exit(0)
try:
FiFlag, isDHCP = False, False
isDHCPlst = []
try:
isDHCPlst=DHCPDiscover()
except:
pass
for host, mac in hostslist.items():
if host in isDHCPlst:
isDHCP = True
else:
isDHCP = False
nm.scan(str(host), arguments="-O")
FiFlag = prettyPrint(host,mac, nm, isDHCP)
if not(FiFlag):
print "["+Fore.YELLOW+"*"+Style.RESET_ALL+"] Warning : couldn't detect to OS"
except Exception, ex:
print "["+Fore.RED+"-"+Style.RESET_ALL+"] Error in OS fingerprinting, continuing..."
def waitForBoot(logger, host):
"""
Wait for a host to be booted in a sense that ssh is ready (using nmap)
:param logger: A logger used for logging possible errors.
:type logger: seealso:: :class:`logging:Logger`
:param host: Host-instance to wait for.
:type host: Host
"""
#find the correct name
name = host.getID() if host.getNameApplied() else host.getTemplate().getID()
#wait for the machine to be ssh-ready
nm = nmap.PortScanner()
logger.info("Boot VM {0}, waiting for SSH".format(name))
isOffline = sshClosed = True
while isOffline or sshClosed:
time.sleep(2)
#scanres = nm.scan(name , '22', '')
try:
remoteServerIP = socket.gethostbyname(name)
except Exception as e:
logger.debug("Unable to resolve hostname '{}'".format(name))
continue
isOffline = False
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex((remoteServerIP, 22))
sock.close()
if not result == 0:
continue
else:
sshClosed = False
logger.info("Host '{0}' is reachable via SSH.".format(name))
#scanres = {}
#logger.info("SCANRES: " + scanres)
#isOffline = scanres['nmap']['scanstats']['uphosts'] == '0'
#if len(list(scanres['scan'].keys())) > 0:
# sshClosed = scanres['scan'][list(scanres['scan'].keys())[0]]['tcp'][22]['state'] == 'closed'
#else:
# logger.info("VM {0} not up yet, keep waiting.".format(name))
#Clean shutdown of the vm
def scan(self):
try:
nm = nmap.PortScanner() # instantiate nmap.PortScanner object
except nmap.PortScannerError:
print('SCAN: Nmap not found', sys.exc_info()[0])
sys.exit(0)
except:
print("SCAN: Unexpected error:", sys.exc_info()[0])
sys.exit(0)
scan_dict = nm.scan(self.target, ports=self.port, arguments=self.options)
print("##############################")
print("REPORT SCAN: ")
print(" IP: "+self.target)
# List other sub domains of target
print(" OTHER SUB DOMAINS:")
for domain, ip in self.dict_domains.items():
if ip == self.target:
print(" "+domain)
# OS details
try:
for osmatch in nm[self.target]['osmatch']:
print(' OS:{0} - {1}%'.format(osmatch['name'], osmatch['accuracy']))
print(' OsClass: {0}|{1}|{2}|{3}|{4}|{5}%'.format(
osmatch['osclass'][0]['type'],
osmatch['osclass'][0]['vendor'],
osmatch['osclass'][0]['osfamily'],
osmatch['osclass'][0]['osgen'],
osmatch['osclass'][0]['osgen'])
)
except:
pass
# TODO: port details, services, etc...
try:
for proto in nm[self.target].all_protocols():
print(' -----PORTS-----')
print(' Protocol : %s' % proto)
lport = list(nm[self.target][proto].keys())
lport.sort()
for port in lport:
print(' PORT : %s\tSTATE : %s' % (port, nm[self.target][proto][port]['state']))
except:
pass
def _update_info(self):
"""Scan the network for devices.
Returns boolean if scanning successful.
"""
_LOGGER.info("Scanning...")
from nmap import PortScanner, PortScannerError
scanner = PortScanner()
options = '-F --host-timeout 5s '
if self.home_interval:
boundary = dt_util.now() - self.home_interval
last_results = [device for device in self.last_results
if device.last_update > boundary]
if last_results:
exclude_hosts = self.exclude + [device.ip for device
in last_results]
else:
exclude_hosts = self.exclude
else:
last_results = []
exclude_hosts = self.exclude
if exclude_hosts:
options += ' --exclude {}'.format(','.join(exclude_hosts))
try:
result = scanner.scan(hosts=' '.join(self.hosts),
arguments=options)
except PortScannerError:
return False
now = dt_util.now()
for ipv4, info in result['scan'].items():
if info['status']['state'] != 'up':
continue
name = info['hostnames'][0]['name'] if info['hostnames'] else ipv4
# Mac address only returned if nmap ran as root
mac = info['addresses'].get('mac') or _arp(ipv4)
if mac is None:
continue
last_results.append(Device(mac.upper(), name, ipv4, now))
self.last_results = last_results
_LOGGER.info("nmap scan successful")
return True