本文整理匯總了Python中nmap.PortScanner方法的典型用法代碼示例。如果您正苦於以下問題:Python nmap.PortScanner方法的具體用法?Python nmap.PortScanner怎麽用?Python nmap.PortScanner使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類nmap
的用法示例。
在下文中一共展示了nmap.PortScanner方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: scan
# 需要導入模塊: import nmap [as 別名]
# 或者: from nmap import PortScanner [as 別名]
def scan(self, hosts: str, ports: str, args: str, sudo: bool = False) -> Dict[str, Any]:
"""
Perform a port scan towards a certain host or network.
:param hosts: Host name/IP or IP subnet to scan (e.g. ``192.168.1.0/24``).
:param ports: Port number, (comma-separated) list or (dash-separated) range to scan (default: all).
:param args: Additional command line arguments for nmap.
:param sudo: Execute nmap as root through sudo (default: ``False``).
:return: Scan results, as an ip -> host map.
"""
import nmap
nm = nmap.PortScanner()
return nm.scan(hosts=hosts, ports=ports, arguments=args, sudo=sudo).get('scan')
# vim:sw=4:ts=4:et:
示例2: osdetect
# 需要導入模塊: import nmap [as 別名]
# 或者: from nmap import PortScanner [as 別名]
def osdetect(ip):
# sys.stdout.write(Bcolors.RED + "\nOS:\n" + Bcolors.ENDC)
nm = nmap.PortScanner()
try:
result = nm.scan(hosts=ip, arguments='-sS -O -vv -n -T4 -p 80,22,443')
for k, v in result.get('scan').items():
if v.get('osmatch'):
for i in v.get('osmatch'):
console('OSdetect', ip, i.get('name') + '\n')
return i.get('name')
else:
break
except (xml.etree.ElementTree.ParseError, nmap.nmap.PortScannerError):
pass
except Exception as e:
console('OSdetect', ip, 'None\n')
logging.exception(e)
示例3: run
# 需要導入模塊: import nmap [as 別名]
# 或者: from nmap import PortScanner [as 別名]
def run(self):
nm = PortScanner()
a=nm.scan(hosts=self.gateway, arguments='-sU --script nbstat.nse -O -p137')
for k,v in a['scan'].iteritems():
if str(v['status']['state']) == 'up':
try:
ip = str(v['addresses']['ipv4'])
hostname = str(v['hostscript'][0]['output']).split(',')[0]
hostname = hostname.split(':')[1]
mac = str(v['hostscript'][0]['output']).split(',')[2]
if search('<unknown>',mac):mac = '<unknown>'
else:mac = mac[13:32]
self.result = ip +'|'+mac.replace('\n','')+'|'+hostname.replace('\n','')
self.emit(SIGNAL('Activated( QString )'),
self.result)
except :
pass
示例4: port_scan
# 需要導入模塊: import nmap [as 別名]
# 或者: from nmap import PortScanner [as 別名]
def port_scan(self,):
host = self.ip
nm = nmap.PortScanner()
self.state = 'scanning'
try:
nm.scan(host) #arguments='-T5 -p 1-65535 -sV -sT -Pn --host-timeout 3600'
ports = nm[host]['tcp'].keys()
report_list = []
for port in ports:
report = {}
state = nm[host]['tcp'][port]['state']
service = nm[host]['tcp'][port]['name']
product = nm[host]['tcp'][port]['product']
report['port'] = port
report['state'] = state
report['service'] = service
report['product'] = product
if state == 'open':
report_list.append(report)
print report_list
self.state = 'scanned'
self.report = json.dumps(report_list)
return json.dumps(report_list)
except Exception as e:
print e
示例5: nmaps
# 需要導入模塊: import nmap [as 別名]
# 或者: from nmap import PortScanner [as 別名]
def nmaps():
try:
print("\033[34mScanning.... Nmap Port Scan: \033[0m" + target)
print ("[+]\033[34m - --> \033[0mThis may take a moment \033[34mBlue Eye\033[0m gathers the data.....\n")
time.sleep(1)
scanner = nmap.PortScanner()
command = ("nmap -Pn " + target)
process = os.popen(command)
results = str(process.read())
logPath = "logs/nmap-" + strftime("%Y-%m-%d_%H:%M:%S", gmtime())
print("\033[34m" + results + command + logPath + "\033[0m")
print("\033[34mNmap Version: \033[0m", scanner.nmap_version())
print ("»"*60 + "\n")
except Exception:
pass
except KeyboardInterrupt:
print("\n")
print("[-] User Interruption Detected..!")
time.sleep(1)
示例6: portscan
# 需要導入模塊: import nmap [as 別名]
# 或者: from nmap import PortScanner [as 別名]
def portscan(self, ctx, host:str, ports:str):
"""Uses nmap to scan the specified ports from the specified host"""
await ctx.channel.trigger_typing()
forbidden_hosts = ["localhost", "0.0.0.0", "127.0.0.1"]
if host in forbidden_hosts:
await ctx.send(Language.get("information.forbidden_host", ctx).format(host))
return
scanner = nmap.PortScanner()
try:
host = socket.gethostbyname(host)
except socket.gaierror:
await ctx.send("`{}` is not a valid address".format(host))
return
ports = scanner.scan(host, ports)["scan"][host]["tcp"]
results = []
for port, data in ports.items():
service = data["name"]
if service == "":
service = Language.get("information.unknown", ctx)
results.append(Language.get("information.port_status", ctx).format(port, service, data["state"]))
await ctx.send(xl.format("\n".join(results)))
示例7: get_ports_from_report
# 需要導入模塊: import nmap [as 別名]
# 或者: from nmap import PortScanner [as 別名]
def get_ports_from_report(nmap_report):
"""
This function is responsible to make a generator object from Nmap report
:param nmap_report: Nmap report location
:return:
"""
scanner = PortScanner()
try:
scan_result = scanner.analyse_nmap_xml_scan(open(nmap_report.strip('"')).read())
for host in scan_result['scan']:
try:
LOGGER.info("%s - Total ports to browse: %d" % (host, len(scan_result['scan'][host]['tcp'])))
for port, port_details in scan_result['scan'][host]['tcp'].items():
try:
yield host, port, port_details
except IndexError:
pass
except KeyError:
pass
except Exception as e:
LOGGER.error("Error: %s" % e)
raise StopIteration
示例8: run
# 需要導入模塊: import nmap [as 別名]
# 或者: from nmap import PortScanner [as 別名]
def run(self):
if not has_nmap:
print_error("To launch this module install nmap (sudo apt install nmap)")
return
print("Trying to get OS")
nm = nmap.PortScanner()
try:
timeout = int(self.args["timeout"])
except:
timeout = 6
result = nm.scan(self.args["rhost"], arguments=f"-O --host-timeout {timeout}")
try:
state = result["scan"][self.args["rhost"]]["status"]["state"]
except:
state = "down"
print_info(f"Host state: <b>{state}</b>")
try:
print_info(f'OS: <b>{result["scan"][self.args["rhost"]]["osmatch"][0]["name"]}</b>')
except:
print_info("OS not found")
示例9: __init__
# 需要導入模塊: import nmap [as 別名]
# 或者: from nmap import PortScanner [as 別名]
def __init__(self, url, ip):
self.is_root()
try:
self.nm = nmap.PortScanner()
except nmap.PortScanner:
colors.error('Nmap not found')
sys.exit(1)
except Exception as e:
print(e)
sys.exit(1)
if url is not None and ip is not None:
colors.error('Please provide either the URL or the IP address...')
sys.exit(1)
if ip is not None:
self.target = ip
elif url is not None:
self.target = self.check_url(url)
else:
colors.error('Please provide URL or the IP address to scan...')
示例10: scan_ssh_hosts
# 需要導入模塊: import nmap [as 別名]
# 或者: from nmap import PortScanner [as 別名]
def scan_ssh_hosts():
"""
Scans all machines on the same network that
have SSH (port 22) enabled
Returns:
IP addresses of hosts
"""
logger.debug("Scanning machines on the same network with port 22 open.")
logger.debug("Gateway: " + gateway)
port_scanner = nmap.PortScanner()
port_scanner.scan(gateway + "/24", arguments='-p 22 --open')
all_hosts = port_scanner.all_hosts()
logger.debug("Hosts: " + str(all_hosts))
return all_hosts
示例11: scan_ftp_hosts
# 需要導入模塊: import nmap [as 別名]
# 或者: from nmap import PortScanner [as 別名]
def scan_ftp_hosts():
"""
Scans all machines on the same network that
have FTP (port 21) enabled
Returns:
IP addresses of hosts
"""
logger.debug("Scanning machines on the same network with port 21 open.")
port_scanner = nmap.PortScanner()
port_scanner.scan(gateway + '/24', arguments='-p 21 --open')
all_hosts = port_scanner.all_hosts()
logger.debug("Hosts: " + str(all_hosts))
return all_hosts
示例12: online
# 需要導入模塊: import nmap [as 別名]
# 或者: from nmap import PortScanner [as 別名]
def online(self,ip):
""" Check if target is online using nmap -sP probe """
# -sP probe could be blocked. Check for common ports.
# there could be solution with socket module.
try:
nm = nmap.PortScanner()
nm.scan(hosts=ip, arguments='-sP')
result = nm[ip].state()
except KeyError:
pass
else:
if result == 'up':
return True
else:
return False
示例13: target_identifier
# 需要導入模塊: import nmap [as 別名]
# 或者: from nmap import PortScanner [as 別名]
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
示例14: run
# 需要導入模塊: import nmap [as 別名]
# 或者: from nmap import PortScanner [as 別名]
def run(self, params={}):
hosts_to_scan = params.get("hosts")
ports_to_scan = params.get("ports")
nmap_args = params.get("arguments")
sudo = params.get("sudo") # defaulted to False
if not len(ports_to_scan):
ports_to_scan = None
if not len(nmap_args):
nmap_args = None
scanner = PortScanner()
try:
scanner.scan(hosts=hosts_to_scan,
ports=ports_to_scan,
arguments=nmap_args,
sudo=sudo)
except PortScannerError as e:
self.logger.error("An error occurred: %s" % e)
else:
scanned_hosts = scanner.all_hosts() # grab hosts that were scanned
results = list(map(lambda host: scanner[host], scanned_hosts)) # create list of scan results
results = komand.helper.clean(results)
return {"result": results}
示例15: test
# 需要導入模塊: import nmap [as 別名]
# 或者: from nmap import PortScanner [as 別名]
def test(self):
scanner = PortScanner()
scanner.scan(hosts="localhost", arguments="-T 4 --max-retries 0 --max-rtt-timeout 100ms")
return {"result": []}