Skip to content

Commit

Permalink
Merge pull request #107 from opinkerfi/okconfig-1.3.4-1
Browse files Browse the repository at this point in the history
Py2/3 fixes
  • Loading branch information
gardart authored Nov 18, 2020
2 parents 6d36717 + 46181c2 commit 8fef58b
Show file tree
Hide file tree
Showing 10 changed files with 79 additions and 64 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ MANIFEST
dist
adagios.conf
*.mo
*.bak

# Created by https://www.gitignore.io/api/python
# Edit at https://www.gitignore.io/?templates=python
Expand Down
36 changes: 22 additions & 14 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -1,26 +1,34 @@
language: python
python:
- "2.7"
- "3.7"
- '2.7'
- '3.7'
install:
- pip install 'pynag>=0.9.1'
- pip install unittest2==1.1.0
- pip install coveralls
- pip install paramiko
- python setup.py build
- pip install 'pynag>=0.9.1'
- pip install unittest2==1.1.0
- pip install coveralls
- pip install paramiko
- pip install future
- python setup.py build
before_script:
- env
- git config --global user.email "[email protected]"
- git config --global user.name "Travis"
- env
- git config --global user.email "[email protected]"
- git config --global user.name "Travis"
script:
- coverage run --source=okconfig tests/test.py
- coverage run --source=okconfig tests/test.py
after_success:
- coveralls
- coveralls
deploy:
provider: pypi
user: gardart
password:
secure: E/DXi3f91+dAoe6+ENQgxEnLMz68oJ5GBlGT/xSD2par0NUQ93sWeIWpXBjxi3ZRRBU4NIaFWfSei/cX81JDLA2h6PmOIer01tByqBlRFDsoPAtQzFgY9lHO8IknbMc59GXZF7vzA71qJaRjxYH8BXowqISTOJnqPJ0qzjC2LDI=
on:
tags: true
branch: master
notifications:
email: false
irc:
channels:
- "chat.freenode.net#okconfig"
- chat.freenode.net#okconfig
on_failure: always
on_success: change

4 changes: 2 additions & 2 deletions okconfig/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ def is_valid():
See verify() for more details
"""
checks = verify()
for result in checks.values():
for result in list(checks.values()):
if result is False: return False
return True

Expand Down Expand Up @@ -550,7 +550,7 @@ def _apply_template(template_name,destination_file, **kwargs):
if not os.path.exists(dirname): os.makedirs(dirname)

fd = open(sourcefile).read()
for old_string,new_string in kwargs.items():
for old_string,new_string in list(kwargs.items()):
fd = fd.replace(old_string,new_string)
open(destination_file,'w').write( fd )
return [destination_file]
Expand Down
1 change: 1 addition & 0 deletions okconfig/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
""" This module provides access to default configuration values in /etc/okconfig.conf """

from __future__ import absolute_import
from builtins import str
import os

# This is the main configuration file
Expand Down
3 changes: 2 additions & 1 deletion okconfig/helper_functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

from __future__ import absolute_import
from __future__ import print_function
from builtins import object
import re
import fcntl
import os
Expand Down Expand Up @@ -96,7 +97,7 @@ def runCommand(command):
return result


class clientInstall:
class clientInstall(object):
import okconfig.config
def __init__(self,
script=okconfig.config.nsclient_installfiles + "/install_nsclient.sh",
Expand Down
2 changes: 1 addition & 1 deletion okconfig/migration_tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -318,7 +318,7 @@ def upgrade_okconfig():
print("Upgrading to version %s" % template_version)
if template_version >= 1:
# "We dont need to do anything, the tools have been upgraded"
pass
pass
if template_version >= 1.1:
upgrade_to_version_1_1()
if template_version >= 2:
Expand Down
3 changes: 2 additions & 1 deletion okconfig/network_scan.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,14 @@

from __future__ import absolute_import
from __future__ import print_function
from builtins import object
import subprocess
import socket
from pynag import Model
from .helper_functions import runCommand
import okconfig

class ScannedHost:
class ScannedHost(object):
"""Simple datastructure for a recently portscanned host"""
def __init__(self, ipaddress=None, hostname=None,ismonitored=None):
self.ipaddress = ipaddress
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,6 @@ def get_filelist(path):
scripts=['usr/bin/okconfig'],
packages=['okconfig'],
requires=['unittest2'],
install_requires=['paramiko','pynag','six'],
install_requires=['paramiko','pynag','six','future'],
data_files=data_files,
)
2 changes: 1 addition & 1 deletion tests/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ def tearDown(self, test=None):
Tear down the fake nagios environment and restore okconfig variables
"""
_environment.terminate()
for var, value in _okconfig_overridden_vars.items():
for var, value in list(_okconfig_overridden_vars.items()):
setattr(okconfig, var, value)

def runTest(*args, **kwargs):
Expand Down
89 changes: 46 additions & 43 deletions usr/bin/okconfig
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@


# No real need to change anything below here
from __future__ import print_function
from builtins import str
from builtins import input
version = "1.3.3"

import sys
Expand Down Expand Up @@ -147,13 +150,13 @@ Run %prog install --help for full list of command line arguments.
opts.user = "root"
if opts.interactive:
if not opts.host:
args.append(raw_input("Remote Host: "))
args.append(input("Remote Host: "))
if not opts.user:
opts.user = raw_input("Username: ")
opts.user = input("Username: ")
if not opts.password or opts.password.lower() == 'ask':
opts.password = getpass.getpass("Password: ")
if method == "winexe" and not opts.domain:
opts.domain = raw_input("Domain: ")
opts.domain = input("Domain: ")

if method == "winexe" and not opts.user:
opts.user = "administrator"
Expand All @@ -168,74 +171,74 @@ Run %prog install --help for full list of command line arguments.
try:
exit_status, stdout, stderr = okconfig.install_okagent(
remote_host=host, domain=opts.domain, username=opts.user, password=opts.password, install_method=method)
except okconfig.OKConfigError, e:
except okconfig.OKConfigError as e:
exit_status = 128
stdout = "Exception occured while running install_okagent"
stderr = str(e)
if exit_status == 0:
print "Install script on %s successful" % (host, )
print("Install script on %s successful" % (host, ))
else:
print "Install script on %s failed with exit_status %s" % (host, exit_status)
print "Output:"
print stdout
print "Errors:"
print stderr
print("Install script on %s failed with exit_status %s" % (host, exit_status))
print("Output:")
print(stdout)
print("Errors:")
print(stderr)
if opts.verbose:
print "Script output:"
print stdout
print("Script output:")
print(stdout)


def verify():
""" Verify that current install of okconfig is functional. """
result = okconfig.verify()
print "Okconfig verification"
print "---------------------"
for k, v in result.items():
print("Okconfig verification")
print("---------------------")
for k, v in list(result.items()):
if v is True:
v = "success"
else:
v = "fail"
print "* %-70s...%s" % (k, v)
print("* %-70s...%s" % (k, v))


def init():
""" Initilize nagios configuration to use okconfig """
print "Initilizating nagios to use okconfig..."
print("Initilizating nagios to use okconfig...")
maincfg = pynag.Parsers.Config().guess_cfg_file()
template_dir = okconfig.config.template_directory
dest_dir = okconfig.config.destination_directory
print "Using configuration file %s" % (maincfg, )
print("Using configuration file %s" % (maincfg, ))
if not os.path.exists(maincfg):
raise okconfig.OKConfigError(
'Error: Nagios configuration file not found under %s' % (maincfg, ))
print "Using Nagios configuration file %s" % (maincfg, )
print("Using Nagios configuration file %s" % (maincfg, ))

c = pynag.Parsers.config(cfg_file=maincfg)
c._edit_static_file(
attribute="cfg_dir", new_value=dest_dir, filename=maincfg)
c._edit_static_file(
attribute="cfg_dir", new_value=template_dir, filename=maincfg)
if not os.path.exists(template_dir):
print "Creating %s" % (template_dir, )
print("Creating %s" % (template_dir, ))
os.makedirs(template_dir)
if not os.path.exists(dest_dir):
print "Creating %s" % (dest_dir,)
print("Creating %s" % (dest_dir,))
os.makedirs(dest_dir)
print 'All Done. Run "%s verify" to verify everything is working' % sys.argv[0]
print('All Done. Run "%s verify" to verify everything is working' % sys.argv[0])


def listhosts():
""" List all available and active hosts in the system """
import pynag.Model
hosts = pynag.Model.Host.objects.filter(register='1')
header = "%-40s%s" % ('host name', 'groups')
print header
print "-" * len(header)
print(header)
print("-" * len(header))
for i in hosts:
print "%-40s%s" % (i.host_name, i.hostgroups)
print("%-40s%s" % (i.host_name, i.hostgroups))
footer = "--- %s hosts found" % (len(hosts))
print footer,
print "-" * (len(header) - len(footer))
print(footer, end=' ')
print("-" * (len(header) - len(footer)))

def listhost():
""" List a single host, useful for verifying if host is present in config """
Expand All @@ -260,21 +263,21 @@ Run %prog listhost --help for full list of command line arguments.
try:
host = pynag.Model.Host.objects.get_by_shortname(opts.host)
header = "%-40s%s" % ('attribute', 'value')
print header
print "-" * len(header)
for key in host.keys():
print(header)
print("-" * len(header))
for key in list(host.keys()):
if key in ['id', 'meta']:
continue
print "%-40s%s" % (key, host.get_attribute(key))
print "-" * len(header)
print("%-40s%s" % (key, host.get_attribute(key)))
print("-" * len(header))
except KeyError:
print "Host not found."
print("Host not found.")


def listtemplates():
""" List all available oktemplates """
for i in okconfig.get_templates():
print i
print(i)


def addgroup():
Expand Down Expand Up @@ -304,7 +307,7 @@ Run %prog addgroup --help for full list of command line arguments.
f = okconfig.addgroup(group_name=group, alias=opts.alias,
force=opts.force)
for i in f:
print "Saved", i
print("Saved", i)


def addcontact():
Expand Down Expand Up @@ -340,7 +343,7 @@ Run %prog addcontact --help for full list of command line arguments.
f = okconfig.addcontact(contact_name=contact, alias=opts.alias,
force=opts.force, group_name=opts.group, email=opts.email)
for i in f:
print "Saved", i
print("Saved", i)


def addtemplate():
Expand Down Expand Up @@ -376,7 +379,7 @@ Run %prog addtemplate --help for full list of command line arguments.
host_name=opts.host, template_name=template_name,
force=opts.force)
for i in f:
print "Saved", i
print("Saved", i)


def addhost():
Expand Down Expand Up @@ -425,7 +428,7 @@ Run %prog addhost --help for full list of command line arguments.
host_name=host, address=opts.address, group_name=opts.group,
use=opts.use, force=opts.force, templates=templates, host_template=opts.ht, alias=opts.alias)
for i in f:
print "Saved", i
print("Saved", i)


def upgrade():
Expand Down Expand Up @@ -455,10 +458,10 @@ Run %prog addservice --help for full list of command line arguments.
service_attributes[key] = value
from pynag import Model
new_service = Model.Service(filename=opts.file)
for k, v in service_attributes.items():
for k, v in list(service_attributes.items()):
new_service[k] = v
new_service.save()
print "# Saved: \n%s \n# To %s" % (new_service, new_service.get_filename())
print("# Saved: \n%s \n# To %s" % (new_service, new_service.get_filename()))


def removehost():
Expand Down Expand Up @@ -486,13 +489,13 @@ Run %prog removehost --help for full list of command line arguments.
"Please specify a host_name on the command line. See --help.")
for i in args:
okconfig.removehost(host_name=i, recursive=opts.recursive)
print "Host %s removed." % (i,)
print("Host %s removed." % (i,))


if __name__ == '__main__':
try:
parse_arguments()
sys.exit(0)
except Exception, e:
print "Error: ", e
except Exception as e:
print("Error: ", e)
sys.exit(1)

0 comments on commit 8fef58b

Please sign in to comment.