1
0
mirror of https://github.com/nmap/nmap.git synced 2025-12-06 12:41:29 +00:00

Apply PEP 8 style guidance to zenmap

Using the pep8 tool (https://pypi.python.org/pypi/pep8), fixed the
following style issues:

Count   Issue
11      E201 whitespace after '['
8       E203 whitespace before ','
41      E211 whitespace before '('
11      E221 multiple spaces before operator
61      E225 missing whitespace around operator
237     E231 missing whitespace after ':'
91      E251 no spaces around keyword / parameter equals
19      E261 at least two spaces before inline comment
41      E301 expected 1 blank line, found 0
200     E302 expected 2 blank lines, found 1
356     E303 too many blank lines (2)
563     E501 line too long (106 characters)
39      E701 multiple statements on one line (colon)
13      E702 multiple statements on one line (semicolon)
4       W291 trailing whitespace
2       W293 blank line contains whitespace
8       W391 blank line at end of file
21      W601 .has_key() is deprecated, use 'in'
2       W602 deprecated form of raising exception

The remaining issues are long lines due to very deep data structures. I
chose not to alter them, as it would involve backslash-continuation
where whitespace is not permitted:

./zenmapGUI/ScanInterface.py:323:80: E501 line too long (90 characters)
./zenmapGUI/ScanInterface.py:456:80: E501 line too long (84 characters)
./zenmapGUI/ScanInterface.py:464:80: E501 line too long (84 characters)
./zenmapGUI/ScanInterface.py:472:80: E501 line too long (122 characters)
./zenmapGUI/ScanInterface.py:479:80: E501 line too long (122 characters)
./zenmapGUI/ScanInterface.py:920:80: E501 line too long (94 characters)
./zenmapGUI/ScanInterface.py:923:80: E501 line too long (93 characters)
./zenmapGUI/MainWindow.py:575:80: E501 line too long (99 characters)
./zenmapGUI/MainWindow.py:906:80: E501 line too long (99 characters)
This commit is contained in:
dmiller
2014-01-08 19:50:22 +00:00
parent 9210a7f1fa
commit 5c662fffdc
100 changed files with 2287 additions and 1814 deletions

View File

@@ -129,7 +129,8 @@ import re
import xml.sax
from zenmapGUI.higwidgets.higwindows import HIGWindow
from zenmapGUI.higwidgets.higboxes import HIGVBox, HIGHBox, HIGSpacer, hig_box_space_holder
from zenmapGUI.higwidgets.higboxes import HIGVBox, HIGHBox, HIGSpacer,\
hig_box_space_holder
from zenmapGUI.higwidgets.higlabels import HIGSectionLabel, HIGEntryLabel
from zenmapGUI.higwidgets.higscrollers import HIGScrolledWindow
from zenmapGUI.higwidgets.higtextviewers import HIGTextView
@@ -149,11 +150,12 @@ from zenmapCore.Name import APP_NAME
paths_config = PathsConfig()
def text_buffer_insert_nsedoc(buf, nsedoc):
"""Inserts NSEDoc at the end of the buffer, with markup turned into proper
tags."""
if not buf.tag_table.lookup("NSEDOC_CODE_TAG"):
buf.create_tag("NSEDOC_CODE_TAG", font = "Monospace")
buf.create_tag("NSEDOC_CODE_TAG", font="Monospace")
for event in zenmapCore.NSEDocParser.nsedoc_parse(nsedoc):
if event.type == "paragraph_start":
buf.insert(buf.get_end_iter(), "\n")
@@ -164,13 +166,15 @@ def text_buffer_insert_nsedoc(buf, nsedoc):
elif event.type == "list_end":
pass
elif event.type == "list_item_start":
buf.insert(buf.get_end_iter(), u"\u2022\u00a0") # bullet nbsp
buf.insert(buf.get_end_iter(), u"\u2022\u00a0") # bullet nbsp
elif event.type == "list_item_end":
buf.insert(buf.get_end_iter(), "\n")
elif event.type == "text":
buf.insert(buf.get_end_iter(), event.text)
elif event.type == "code":
buf.insert_with_tags_by_name(buf.get_end_iter(), event.text, "NSEDOC_CODE_TAG")
buf.insert_with_tags_by_name(
buf.get_end_iter(), event.text, "NSEDOC_CODE_TAG")
class ScriptHelpXMLContentHandler (xml.sax.handler.ContentHandler):
"""A very simple parser for --script-help XML output. This could extract
@@ -183,11 +187,13 @@ class ScriptHelpXMLContentHandler (xml.sax.handler.ContentHandler):
def startElement(self, name, attrs):
if name == u"directory":
if not attrs.has_key(u"name"):
raise ValueError(u"\"directory\" element did not have \"name\" attribute")
if u"name" not in attrs:
raise ValueError(
u'"directory" element did not have "name" attribute')
dirname = attrs[u"name"]
if not attrs.has_key(u"path"):
raise ValueError(u"\"directory\" element did not have \"path\" attribute")
if u"path" not in attrs:
raise ValueError(
u'"directory" element did not have "path" attribute')
path = attrs[u"path"]
if dirname == u"scripts":
self.scripts_dir = path
@@ -197,8 +203,9 @@ class ScriptHelpXMLContentHandler (xml.sax.handler.ContentHandler):
# Ignore.
pass
elif name == u"script":
if not attrs.has_key(u"filename"):
raise ValueError(u"\"script\" element did not have \"filename\" attribute")
if u"filename" not in attrs:
raise ValueError(
u'"script" element did not have "filename" attribute')
self.script_filenames.append(attrs[u"filename"])
@staticmethod
@@ -209,6 +216,7 @@ class ScriptHelpXMLContentHandler (xml.sax.handler.ContentHandler):
parser.parse(f)
return handler
class ScriptInterface:
# Timeout, in milliseconds, after the user stops typing and we update the
# interface from --script.
@@ -216,9 +224,9 @@ class ScriptInterface:
# Timeout, in milliseconds, between polls of the Nmap subprocess.
NMAP_DELAY = 200
def __init__(self,root_tabs,ops,update_command,help_buf):
self.hmainbox = HIGHBox(False,0)
self.notscripttab = False # to show profile editor that it is a script tab
def __init__(self, root_tabs, ops, update_command, help_buf):
self.hmainbox = HIGHBox(False, 0)
self.notscripttab = False # show profile editor it is a script tab
self.nmap_process = None
self.script_list_timeout_id = None
self.nmap_timeout_id = None
@@ -240,16 +248,16 @@ class ScriptInterface:
# Arg name, arg value, (name, desc) tuple.
self.arg_liststore = gtk.ListStore(str, str, object)
# This is what is shown initially. After the initial Nmap run to get the
# list of script is finished, this will be replaced with a TreeView
# This is what is shown initially. After the initial Nmap run to get
# the list of script is finished, this will be replaced with a TreeView
# showing the scripts or an error message.
self.script_list_container = gtk.VBox()
self.script_list_container.pack_start(self.make_please_wait_widget())
self.hmainbox.pack_start(self.script_list_container, False, False, 0)
self.nmap_error_widget = gtk.Label(_("""\
There was an error getting the list of scripts from Nmap. Try upgrading Nmap.\
"""))
self.nmap_error_widget = gtk.Label(_(
"There was an error getting the list of scripts from Nmap. "
"Try upgrading Nmap."))
self.nmap_error_widget.set_line_wrap(True)
self.nmap_error_widget.show_all()
@@ -269,8 +277,8 @@ There was an error getting the list of scripts from Nmap. Try upgrading Nmap.\
def get_script_list(self, rules, callback):
"""Start an Nmap subprocess in the background with
"--script-help=<rules> -oX -", and set it up to call the given callback when
finished."""
"--script-help=<rules> -oX -", and set it up to call the given callback
when finished."""
ops = NmapOptions()
ops.executable = paths_config.nmap_command_path
@@ -279,11 +287,12 @@ There was an error getting the list of scripts from Nmap. Try upgrading Nmap.\
command_string = ops.render_string()
# Separate stderr to avoid breaking XML parsing with "Warning: File
# ./nse_main.lua exists, but Nmap is using...".
stderr = tempfile.TemporaryFile(mode = "rb", prefix = APP_NAME + "-script-help-stderr-")
stderr = tempfile.TemporaryFile(
mode="rb", prefix=APP_NAME + "-script-help-stderr-")
log.debug("Script interface: running %s" % repr(command_string))
nmap_process = NmapCommand(command_string)
try:
nmap_process.run_scan(stderr = stderr)
nmap_process.run_scan(stderr=stderr)
except Exception, e:
callback(False, None)
stderr.close()
@@ -292,14 +301,17 @@ There was an error getting the list of scripts from Nmap. Try upgrading Nmap.\
self.script_list_widget.set_sensitive(False)
gobject.timeout_add(self.NMAP_DELAY, self.script_list_timer_callback, nmap_process, callback)
gobject.timeout_add(
self.NMAP_DELAY, self.script_list_timer_callback,
nmap_process, callback)
def script_list_timer_callback(self, process, callback):
try:
status = process.scan_state()
except:
status = None
log.debug("Script interface: script_list_timer_callback %s" % repr(status))
log.debug("Script interface: script_list_timer_callback %s" % \
repr(status))
if status == True:
# Still running, schedule this timer to check again.
@@ -326,7 +338,8 @@ There was an error getting the list of scripts from Nmap. Try upgrading Nmap.\
def handle_initial_script_list_output(self, process):
process.stdout_file.seek(0)
try:
handler = ScriptHelpXMLContentHandler.parse_nmap_script_help(process.stdout_file)
handler = ScriptHelpXMLContentHandler.parse_nmap_script_help(
process.stdout_file)
except (ValueError, xml.sax.SAXParseException), e:
log.debug("--script-help parse exception: %s" % str(e))
return False
@@ -342,12 +355,14 @@ There was an error getting the list of scripts from Nmap. Try upgrading Nmap.\
log.debug("--script-help error: no nselib directory")
return False
log.debug("Script interface: scripts dir %s" % repr(handler.scripts_dir))
log.debug("Script interface: nselib dir %s" % repr(handler.nselib_dir))
log.debug("Script interface: scripts dir %s" % repr(
handler.scripts_dir))
log.debug("Script interface: nselib dir %s" % repr(handler.nselib_dir))
# Make a dict of script metadata entries.
entries = {}
for entry in get_script_entries(handler.scripts_dir, handler.nselib_dir):
for entry in get_script_entries(
handler.scripts_dir, handler.nselib_dir):
entries[entry.filename] = entry
self.liststore.clear()
@@ -367,7 +382,8 @@ There was an error getting the list of scripts from Nmap. Try upgrading Nmap.\
def update_script_list_from_spec(self, spec):
"""Callback method for user edit delay."""
log.debug("Script interface: update_script_list_from_spec %s" % repr(spec))
log.debug("Script interface: update_script_list_from_spec %s" % repr(
spec))
if spec:
self.get_script_list(spec, self.update_script_list_cb)
else:
@@ -383,7 +399,8 @@ There was an error getting the list of scripts from Nmap. Try upgrading Nmap.\
def handle_update_script_list_output(self, process):
process.stdout_file.seek(0)
try:
handler = ScriptHelpXMLContentHandler.parse_nmap_script_help(process.stdout_file)
handler = ScriptHelpXMLContentHandler.parse_nmap_script_help(
process.stdout_file)
except (ValueError, xml.sax.SAXParseException), e:
log.debug("--script-help parse exception: %s" % str(e))
return False
@@ -422,29 +439,41 @@ There was an error getting the list of scripts from Nmap. Try upgrading Nmap.\
character."""
if self.script_list_timeout_id:
gobject.source_remove(self.script_list_timeout_id)
self.script_list_timeout_id = gobject.timeout_add(self.SCRIPT_LIST_DELAY, self.update_script_list_from_spec, spec)
self.script_list_timeout_id = gobject.timeout_add(
self.SCRIPT_LIST_DELAY,
self.update_script_list_from_spec, spec)
def parse_script_args(self,raw_argument):
def parse_script_args(self, raw_argument):
"""When the command line is edited, this function is called to update
the script arguments display according to the value of --script-args."""
the script arguments display according to the value of
--script-args."""
arg_dict = parse_script_args_dict(raw_argument)
if arg_dict is None: # if there is parsing error args_dict holds none
if arg_dict is None: # if there is parsing error args_dict holds none
self.arg_values.clear()
else:
for key in arg_dict.keys():
self.arg_values[key] = arg_dict[key]
def update_argument_values(self,raw_argument):
def update_argument_values(self, raw_argument):
"""When scripting tab starts up, argument values are updated."""
if raw_argument is not None:
self.parse_script_args(raw_argument)
def set_help_texts(self):
"""Sets the help texts to be displayed."""
self.list_scripts_help = _("List of scripts\n\nA list of all installed scripts. Activate or deactivate a script by clicking the box next to the script name.")
self.description_help = _("Description\n\nThis box shows the categories a script belongs to. In addition, it gives a detailed description of the script which is present in script. A URL points to online NSEDoc documentation.")
self.argument_help = _("Arguments\n\nA list of arguments that affect the selected script. Enter a value by clicking in the value field beside the argument name.")
self.list_scripts_help = _("""List of scripts
A list of all installed scripts. Activate or deactivate a script \
by clicking the box next to the script name.""")
self.description_help = _("""Description
This box shows the categories a script belongs to. In addition, it gives a \
detailed description of the script which is present in script. A URL points \
to online NSEDoc documentation.""")
self.argument_help = _("""Arguments
A list of arguments that affect the selected script. Enter a value by \
clicking in the value field beside the argument name.""")
def make_please_wait_widget(self):
vbox = gtk.VBox()
@@ -454,7 +483,8 @@ There was an error getting the list of scripts from Nmap. Try upgrading Nmap.\
return vbox
def make_script_list_widget(self):
"""Creates and packs widgets associated with left hand side of Interface."""
"""Creates and packs widgets associated with left hand side of
Interface."""
vbox = gtk.VBox()
scrolled_window = HIGScrolledWindow()
@@ -485,7 +515,8 @@ There was an error getting the list of scripts from Nmap. Try upgrading Nmap.\
vbox.pack_start(scrolled_window, True, True, 0)
self.file_scrolled_window = HIGScrolledWindow()
self.file_scrolled_window.set_policy(gtk.POLICY_ALWAYS, gtk.POLICY_ALWAYS)
self.file_scrolled_window.set_policy(
gtk.POLICY_ALWAYS, gtk.POLICY_ALWAYS)
self.file_scrolled_window.set_size_request(175, -1)
self.file_scrolled_window.hide()
self.file_scrolled_window.set_no_show_all(True)
@@ -511,11 +542,12 @@ There was an error getting the list of scripts from Nmap. Try upgrading Nmap.\
vbox.pack_start(self.file_scrolled_window, False)
hbox = HIGHBox(False, 2)
self.remove_file_button = HIGButton(stock = gtk.STOCK_REMOVE)
self.remove_file_button.connect("clicked", self.remove_file_button_clicked_cb)
self.remove_file_button = HIGButton(stock=gtk.STOCK_REMOVE)
self.remove_file_button.connect(
"clicked", self.remove_file_button_clicked_cb)
self.remove_file_button.set_sensitive(False)
hbox.pack_end(self.remove_file_button)
add_file_button = HIGButton(stock = gtk.STOCK_ADD)
add_file_button = HIGButton(stock=gtk.STOCK_ADD)
add_file_button.connect("clicked", self.add_file_button_clicked_cb)
hbox.pack_end(add_file_button)
@@ -542,7 +574,7 @@ There was an error getting the list of scripts from Nmap. Try upgrading Nmap.\
else:
self.file_liststore.append([filename, True])
def strip_file_name(self,filename):
def strip_file_name(self, filename):
"""Removes a ".nse" extension from filename if present."""
if(filename.endswith(".nse")):
return filename[:-4]
@@ -579,8 +611,8 @@ There was an error getting the list of scripts from Nmap. Try upgrading Nmap.\
text_view = gtk.TextView()
text_view.connect("enter-notify-event", self.update_help_desc_cb)
self.text_buffer = text_view.get_buffer()
self.text_buffer.create_tag("Usage", font = "Monospace")
self.text_buffer.create_tag("Output", font = "Monospace")
self.text_buffer.create_tag("Usage", font="Monospace")
self.text_buffer.create_tag("Output", font="Monospace")
text_view.set_wrap_mode(gtk.WRAP_WORD)
text_view.set_editable(False)
text_view.set_justification(gtk.JUSTIFY_LEFT)
@@ -606,7 +638,7 @@ There was an error getting the list of scripts from Nmap. Try upgrading Nmap.\
arg_listview.append_column(val_col)
arg_col.pack_start(argument, True)
arg_col.add_attribute(argument, "text", 0)
val_col.pack_start(self.value,True)
val_col.pack_start(self.value, True)
val_col.add_attribute(self.value, "text", 1)
arg_window.add(arg_listview)
@@ -614,7 +646,7 @@ There was an error getting the list of scripts from Nmap. Try upgrading Nmap.\
return vbox
def value_edited_cb(self,cell,path,new_text,model):
def value_edited_cb(self, cell, path, new_text, model):
"""Called when the argument cell is edited."""
self.arg_list = []
model[path][1] = new_text
@@ -637,21 +669,22 @@ There was an error getting the list of scripts from Nmap. Try upgrading Nmap.\
self.ops["--script-args"] = ",".join(self.arg_list)
self.update_command()
def selection_changed_cb(self,selection):
def selection_changed_cb(self, selection):
"""Called back when the list of scripts is selected."""
model, selection = selection.get_selected_rows()
for path in selection:
check_value = model.get_value(model.get_iter(path),1)
entry = model.get_value(model.get_iter(path),2)
check_value = model.get_value(model.get_iter(path), 1)
entry = model.get_value(model.get_iter(path), 2)
self.set_description(entry)
self.populate_arg_list(entry)
self.focussedentry = entry #Remember the currently pointing script entry
# Remember the currently pointing script entry
self.focussedentry = entry
def update_help_ls_cb(self,widget,extra): # list of scripts
def update_help_ls_cb(self, widget, extra): # list of scripts
"""Callback method to display the help for the list of scripts."""
self.help_buf.set_text(self.list_scripts_help)
def update_help_desc_cb(self,widget,extra):
def update_help_desc_cb(self, widget, extra):
"""Callback method for displaying description."""
self.help_buf.set_text(self.description_help)
@@ -672,14 +705,17 @@ There was an error getting the list of scripts from Nmap. Try upgrading Nmap.\
arg_name, arg_desc = model.get_value(model.get_iter(path), 2)
if arg_desc is not None:
self.help_buf.set_text("")
self.help_buf.insert(self.help_buf.get_end_iter(), text = "%s\n" % arg_name)
self.help_buf.insert(
self.help_buf.get_end_iter(), text="%s\n" % arg_name)
text_buffer_insert_nsedoc(self.help_buf, arg_desc)
else:
self.help_buf.set_text("")
def add_file_button_clicked_cb(self, button):
if self.script_file_chooser is None:
self.script_file_chooser = zenmapGUI.FileChoosers.ScriptFileChooserDialog(title = _("Select script files"))
self.script_file_chooser = \
zenmapGUI.FileChoosers.ScriptFileChooserDialog(
title=_("Select script files"))
response = self.script_file_chooser.run()
filenames = self.script_file_chooser.get_filenames()
self.script_file_chooser.hide()
@@ -702,7 +738,7 @@ There was an error getting the list of scripts from Nmap. Try upgrading Nmap.\
self.remove_file_button.set_sensitive(False)
self.set_script_from_selection()
def set_description(self,entry):
def set_description(self, entry):
"""Sets the content that is to be displayed in the description box."""
self.text_buffer.set_text(u"")
@@ -711,20 +747,25 @@ Categories: %(cats)s
""" % {"cats": ", ".join(entry.categories)})
text_buffer_insert_nsedoc(self.text_buffer, entry.description)
if entry.usage:
self.text_buffer.insert(self.text_buffer.get_end_iter(), "\nUsage\n")
self.text_buffer.insert_with_tags_by_name(self.text_buffer.get_end_iter(), entry.usage, "Usage")
self.text_buffer.insert(
self.text_buffer.get_end_iter(), "\nUsage\n")
self.text_buffer.insert_with_tags_by_name(
self.text_buffer.get_end_iter(), entry.usage, "Usage")
if entry.output:
self.text_buffer.insert(self.text_buffer.get_end_iter(), "\nOutput\n")
self.text_buffer.insert_with_tags_by_name(self.text_buffer.get_end_iter(), entry.output, "Output")
self.text_buffer.insert(
self.text_buffer.get_end_iter(), "\nOutput\n")
self.text_buffer.insert_with_tags_by_name(
self.text_buffer.get_end_iter(), entry.output, "Output")
if entry.url:
self.text_buffer.insert(self.text_buffer.get_end_iter(), "\n" + entry.url)
self.text_buffer.insert(
self.text_buffer.get_end_iter(), "\n" + entry.url)
def populate_arg_list(self,entry):
def populate_arg_list(self, entry):
"""Called when a particular script is hovered over to display its
arguments and values (if any)."""
self.arg_liststore.clear()
self.current_arguments = []
self.value.set_property('editable',True)
self.value.set_property('editable', True)
for arg in entry.arguments:
arg_name, arg_desc = arg
self.current_arguments.append(arg)