Exemplo n.º 1
0
def main():
    p = sacliutil.standardOptions("tokenstore --username=<user> [ <action> ]")
    (options,arguments) = p.parse_args()
    # don't really need to get SALib instantiated.
    # s = sacliutil.getSALib(options.username,options.password)

    if options.debug:
        s.setDebug(1)
    action = ['create']
    if options.authfile or options.username:
        if arguments:
            if re.match('[Cc]reate',arguments[0]):
                if options.authfile:
                    authpath = os.path.split(options.authfile)
                    (tokenpath,tokenfile) = authpath
                else:
                    tokenpath = "%s/%s" % (sacliutil.getHomeDir(),sacliutil.defaultTokenDir)
                    tokenfile = "%s" % (options.username)            
                if not tokenfile:
                    raise SALib.InvalidArgs,authpath
                if not os.path.isdir(tokenpath):
                    os.makedirs(tokenpath,0700)
                tokenfilepath = tokenpath + "/" + tokenfile
                tkfd = os.open(tokenfilepath,os.O_RDWR|os.O_CREAT,0400)
                bytes = os.write(tkfd,SALib.getToken(username=options.username,password=options.password))
                os.close(tkfd)
        else:
            p.print_help()
            print "You have to provide either --authfile=<token filename> or --username=<username> with the actions: %s" % sacliutil.getActionList(action)
    else:
        p.print_help()
        print "You have to provide either --authfile=<token filename> or --username=<username> with the actions: %s" % sacliutil.getActionList(action)
Exemplo n.º 2
0
def main():
    p = sacliutil.standardOptions("platform --id=<platform name or id> [--<modifier options>] [ <action> ]")
    p.add_option('--id', help="Use to match platforms.")
    (options,arguments) = p.parse_args()
    s = sacliutil.getSALib(options.username,options.password,options.authfile)

    if options.debug:
        s.setDebug(1)
    if options.id:
        action = ['list']
        if arguments:
            if re.match('[Ll]ist',arguments[0]):
                if options.regex:
                    platformRefsList = s.getPlatformRefs(options.id,True)
                else:
                    platformRefsList = s.getPlatformRefs(options.id)
                for i in platformRefsList:
                    print "%s" % i
                    #platformVO = s.callUAPI('device.PlatformService', 'getPlatformVO', i)
                    #print "%s|PlatformRef:%s" % (platformVO.name,i.id)
            else:
                p.print_help()
                print "Please provide an action: %s" % sacliutil.getActionList(action)
        else:
            p.print_help()
            print "Please provide an action: %s" % sacliutil.getActionList(action)
    else:
        p.print_help()
Exemplo n.º 3
0
def main():
    p = sacliutil.standardOptions(
        "platform --id=<platform name or id> [--<modifier options>] [ <action> ]"
    )
    p.add_option('--id', help="Use to match platforms.")
    (options, arguments) = p.parse_args()
    s = sacliutil.getSALib(options.username, options.password,
                           options.authfile)

    if options.debug:
        s.setDebug(1)
    if options.id:
        action = ['list']
        if arguments:
            if re.match('[Ll]ist', arguments[0]):
                if options.regex:
                    platformRefsList = s.getPlatformRefs(options.id, True)
                else:
                    platformRefsList = s.getPlatformRefs(options.id)
                for i in platformRefsList:
                    print "%s" % i
                    #platformVO = s.callUAPI('device.PlatformService', 'getPlatformVO', i)
                    #print "%s|PlatformRef:%s" % (platformVO.name,i.id)
            else:
                p.print_help()
                print "Please provide an action: %s" % sacliutil.getActionList(
                    action)
        else:
            p.print_help()
            print "Please provide an action: %s" % sacliutil.getActionList(
                action)
    else:
        p.print_help()
Exemplo n.º 4
0
def main():
    p = sacliutil.standardOptions("customer --id=<customer name> [ <action> ]")
    p.add_option('--id', help="To specify pattern to match customer.")
    (options, arguments) = p.parse_args()
    s = sacliutil.getSALib(options.username, options.password,
                           options.authfile)

    if options.debug:
        s.setDebug(1)
    if options.id:
        action = ['list']
        if arguments:
            if re.match('[Ll]ist', arguments[0]):
                if options.regex:
                    customerRefsList = s.getCustomerRefs(options.id, True)
                else:
                    customerRefsList = s.getCustomerRefs(options.id)
                for i in customerRefsList:
                    print "%s" % i
            else:
                p.print_help()
                print "Please provide an action: %s" % sacliutil.getActionList(
                    action)
        else:
            p.print_help()
            print "Please provide an action: %s" % sacliutil.getActionList(
                action)
    else:
        p.print_help()
Exemplo n.º 5
0
def main():
    p = sacliutil.standardOptions("customer --id=<customer name> [ <action> ]")
    p.add_option('--id', help="To specify pattern to match customer.")
    (options,arguments) = p.parse_args()
    s = sacliutil.getSALib(options.username,options.password,options.authfile)

    if options.debug:
        s.setDebug(1)
    if options.id:
        action = ['list']
        if arguments:
            if re.match('[Ll]ist',arguments[0]):
                if options.regex:
                    customerRefsList = s.getCustomerRefs(options.id,True)
                else:
                    customerRefsList = s.getCustomerRefs(options.id)
                for i in customerRefsList:
                    print "%s" % i
            else:
                p.print_help()
                print "Please provide an action: %s" % sacliutil.getActionList(action)
        else:
            p.print_help()
            print "Please provide an action: %s" % sacliutil.getActionList(action)
    else:
        p.print_help()
Exemplo n.º 6
0
def main():
    p = sacliutil.standardOptions(
        "customfield --customfield=<customfield name> [ <action> ]")
    p.add_option('--customfield', help="Specify a customfield.")
    (options, arguments) = p.parse_args()
    s = sacliutil.getSALib(options.username, options.password,
                           options.authfile)

    if options.debug:
        s.setDebug(1)
    if options.customfield:
        action = ['create', 'delete']
        if arguments:
            if arguments[0] == 'create':
                s.createCustomField(options.customfield)
            elif arguments[0] == 'delete':
                s.deleteCustomField(options.customfield)
            else:
                p.print_help()
                print "You must provide an action: %s" % sacliutil.getActionList(
                    action)
        else:
            p.print_help()
            print "You must provide an action: %s" % sacliutil.getActionList(
                action)
    else:
        p.print_help()
Exemplo n.º 7
0
def main():
    p = sacliutil.standardOptions("")
    (options,arguments) = p.parse_args()
    s = sacliutil.getSALib(options.username,options.password,options.authfile)

    if options.debug:
        s.setDebug(1)

    s.cacheRefresh()
    print "Cache has been refreshed."
Exemplo n.º 8
0
def main():
    p = sacliutil.standardOptions("")
    p.add_option('--jobid', help="OS Sequence Job ID from HPSA.")
    p.add_option('--server', help="Server ID or Name.")
    (options, arguments) = p.parse_args()
    s = sacliutil.getSALib(options.username, options.password,
                           options.authfile)

    if options.debug:
        s.setDebug(1)
    if options.jobid and options.server:
        print "%s" % get_sp_jobid(s, options.jobid, options.server)
    else:
        p.print_help()
Exemplo n.º 9
0
def main():
    p = sacliutil.standardOptions("")
    p.add_option('--id', help="Specify ID or APX name.")
    p.add_option('--notification',
                 action="store_true",
                 help="Emails notification to the user.")
    p.add_option('--ticketid', help="Ticket ID to assign the APX.")
    p.add_option('--args', help="Arguments to pass to the APX.")
    (options, arguments) = p.parse_args()
    s = sacliutil.getSALib(options.username, options.password,
                           options.authfile)

    if options.debug:
        s.setDebug(1)
    if options.id:
        action = ['run', 'list']
        if arguments:
            if re.match('[Rr]un', arguments[0]):
                if options.args:
                    args = options.args
                else:
                    args = ''
                if options.ticketid:
                    ticketid = options.ticketid
                else:
                    ticketid = None
                jobid = s.startProgramAPX(options.id, args,
                                          options.notification, ticketid)
                print "%s" % jobid
            elif re.match('[Ll]ist', arguments[0]):
                for i in s.getAPXRefs(options.id):
                    print "%s" % i
            else:
                p.print_help()
                print "Please provide an action: %s" % sacliutil.getActionList(
                    action)
        else:
            p.print_help()
            print "Please provide an action: %s" % sacliutil.getActionList(
                action)
    else:
        p.print_help()
Exemplo n.º 10
0
def main():
    p = sacliutil.standardOptions("tokenstore --username=<user> [ <action> ]")
    (options, arguments) = p.parse_args()
    # don't really need to get SALib instantiated.
    # s = sacliutil.getSALib(options.username,options.password)

    if options.debug:
        s.setDebug(1)
    action = ['create']
    if options.authfile or options.username:
        if arguments:
            if re.match('[Cc]reate', arguments[0]):
                if options.authfile:
                    authpath = os.path.split(options.authfile)
                    (tokenpath, tokenfile) = authpath
                else:
                    tokenpath = "%s/%s" % (sacliutil.getHomeDir(),
                                           sacliutil.defaultTokenDir)
                    tokenfile = "%s" % (options.username)
                if not tokenfile:
                    raise SALib.InvalidArgs, authpath
                if not os.path.isdir(tokenpath):
                    os.makedirs(tokenpath, 0700)
                tokenfilepath = tokenpath + "/" + tokenfile
                tkfd = os.open(tokenfilepath, os.O_RDWR | os.O_CREAT, 0400)
                bytes = os.write(
                    tkfd,
                    SALib.getToken(username=options.username,
                                   password=options.password))
                os.close(tkfd)
        else:
            p.print_help()
            print "You have to provide either --authfile=<token filename> or --username=<username> with the actions: %s" % sacliutil.getActionList(
                action)
    else:
        p.print_help()
        print "You have to provide either --authfile=<token filename> or --username=<username> with the actions: %s" % sacliutil.getActionList(
            action)
Exemplo n.º 11
0
def main():
    p = sacliutil.standardOptions("customfield --customfield=<customfield name> [ <action> ]")
    p.add_option('--customfield', help="Specify a customfield.")
    (options,arguments) = p.parse_args()
    s = sacliutil.getSALib(options.username,options.password,options.authfile)

    if options.debug:
        s.setDebug(1)
    if options.customfield:
        action = ['create','delete']
        if arguments:
            if arguments[0] == 'create':
                s.createCustomField(options.customfield)
            elif arguments[0] == 'delete':
                s.deleteCustomField(options.customfield)
            else:
                p.print_help()
                print "You must provide an action: %s" % sacliutil.getActionList(action)
        else:
            p.print_help()
            print "You must provide an action: %s" % sacliutil.getActionList(action)
    else:
        p.print_help()
Exemplo n.º 12
0
def main():
    p = sacliutil.standardOptions("")
    p.add_option('--id', help="Specify ID or APX name.")
    p.add_option('--notification', action="store_true",help="Emails notification to the user.")
    p.add_option('--ticketid', help="Ticket ID to assign the APX.")
    p.add_option('--args', help="Arguments to pass to the APX.")
    (options,arguments) = p.parse_args()
    s = sacliutil.getSALib(options.username,options.password,options.authfile)

    if options.debug:
        s.setDebug(1)
    if options.id:
        action = ['run','list']
        if arguments:
            if re.match('[Rr]un',arguments[0]):
                if options.args:
                    args = options.args
                else:
                    args = ''
                if options.ticketid:
                    ticketid = options.ticketid
                else:
                    ticketid = None
                jobid = s.startProgramAPX(options.id,args,options.notification,ticketid)
                print "%s" % jobid
            elif re.match('[Ll]ist',arguments[0]):
                for i in s.getAPXRefs(options.id):
                    print "%s" % i
            else:
                p.print_help()
                print "Please provide an action: %s" % sacliutil.getActionList(action)
        else:
            p.print_help()
            print "Please provide an action: %s" % sacliutil.getActionList(action)
    else:
        p.print_help()
Exemplo n.º 13
0
def main():
    p = sacliutil.standardOptions(
        "job --id=<jobid> [--<modifier options>] [ <action> ]")
    p.add_option('--id', help="Use to find SA jobs.")
    (options, arguments) = p.parse_args()
    s = sacliutil.getSALib(options.username, options.password,
                           options.authfile)

    if options.debug:
        s.setDebug(1)
    if options.id:
        action = ['results']
        if arguments:
            if re.match('[Rr]esults?', arguments[0]):
                jobType = s.getJobResults(options.id)['type']
                jobResultDict = s.getJobResults(options.id)['hosts']
                hostKeys = jobResultDict.keys()
                hostKeys.sort()
                for host in hostKeys:
                    if jobType == 'server.script.run':
                        print '-------------------------------------------------------------------------------'
                        print "%s" % host
                        jobResults = jobResultDict[host].keys()
                        jobResults.sort()
                        for i in jobResults:
                            if re.match(
                                    '(stderr|stdout|tailStderr|tailStdout)',
                                    i):
                                print "%s:\n%s" % (i, jobResultDict[host][i])
                            else:
                                print "%s: %s" % (i, jobResultDict[host][i])
                        print '-------------------------------------------------------------------------------'
                        print
                    elif jobType == 'server.os.install':
                        if jobResultDict[host].error:
                            print "FAILED OS Provisioning on %s with JobID %s" % (
                                host, options.id)
                            print "%s" % jobResultDict[host].error.message
                        else:
                            print "COMPLETED OS Provisioning on %s with JobID %s" % (
                                host, options.id)
                            minusInstallProfile = re.sub(r'(-+[A-Za-z0-9. /]*-+\n)(.*\n)*(-+[A-Za-z0-9_. /]*-+\n)',\
                                                         '',\
                                                        jobResultDict[host].elemResultInfo[0].message.defaultMsg,re.MULTILINE)
                            print "%s" % minusInstallProfile
                    elif jobType == 'ogfs.script.run':
                        print "OGFS Host: %s" % host
                        print "JobRef: %s" % jobResultDict[host].jobInfo.ref
                        print "script: %s" % jobResultDict[host].jobInfo.script
                        print "start date: %s" % time.strftime(
                            "%a %b %d %H:%M:%S %Z %Y",
                            time.localtime(
                                jobResultDict[host].jobInfo.startDate))
                        print "end date: %s" % time.strftime(
                            "%a %b %d %H:%M:%S %Z %Y",
                            time.localtime(
                                jobResultDict[host].jobInfo.endDate))
                        print "parameters: %s" % jobResultDict[
                            host].jobInfo.args.parameters
                        print "timeout: %s" % jobResultDict[
                            host].jobInfo.args.timeOut
                        print "workingDir: %s" % jobResultDict[
                            host].jobInfo.args.workingDir
                        print "stdout: %s" % jobResultDict[
                            host].jobOutput.tailStdout
                    elif jobType == 'program_apx.execute':
                        print "OGFS Host: %s" % host
                        print "JobRef: %s" % jobResultDict[host].jobInfo.ref
                        print "version: %s" % jobResultDict[
                            host].jobInfo.version
                        print "apx: %s" % jobResultDict[host].jobInfo.APX
                        print "start date: %s" % time.strftime(
                            "%a %b %d %H:%M:%S %Z %Y",
                            time.localtime(
                                jobResultDict[host].jobInfo.startDate))
                        print "end date: %s" % time.strftime(
                            "%a %b %d %H:%M:%S %Z %Y",
                            time.localtime(
                                jobResultDict[host].jobInfo.endDate))
                        print "parameters: %s" % jobResultDict[
                            host].jobInfo.args.parameters
                        print "timeout: %s" % jobResultDict[
                            host].jobInfo.args.timeOut
                        print "workingDir: %s" % jobResultDict[
                            host].jobInfo.args.workingDir
                    elif jobType == 'server.swpolicy.remediate':
                        job_id = string.atol(options.id)
                        j = s.getJobResultsMap(job_id)
                        print "Software Policy JobID %s: %s" % (
                            options.id, s.getJobResults(
                                options.id)['hosts'][options.id])
                        for server_id, job_results in j[
                                'host_progress_dic'].iteritems():
                            print "%s: %s" % (s.getServerRefs(server_id)[0],
                                              job_results['status'])
            else:
                p.print_help()
                print "Please provide an action: %s" % sacliutil.getActionList(
                    action)
        else:
            p.print_help()
            print "Please provide an action: %s" % sacliutil.getActionList(
                action)
    else:
        p.print_help()
Exemplo n.º 14
0
def main():
    p = sacliutil.standardOptions("appconfig --id=<identifier> [--<modifier options>] [ <action> ]")
    p.add_option('--id', help="Specify identifier for appconfig.")
    p.add_option('--server', help="Specify server pattern for appconfig.")
    p.add_option('--name', help="Specifies name valueset of the appconfig.")
    p.add_option('--value', help="Specifies value valueset of the appconfig.")
    p.add_option('--matchstr', help="search string for replacement by --value.")
    p.add_option('--clonename', help="Specifies appconfig clone name.")
    p.add_option('--customer', help="Specify servers by customer name.")
    p.add_option('--facility', help="Specifies servers by facility name.")
    p.add_option('--platform', help="Specify platform by id, name, or pattern.")
    p.add_option('--scope',default='all',help="specify either appconfig,customer,facility,devicegroup,server,or all")
    p.add_option('--show', action="store_true",help="Show before and after valueset changes.")
    p.add_option('--dryrun', action="store_true",help="Do a dry run of valuereplace.")
    (options, arguments) = p.parse_args()
    s = sacliutil.getSALib(options.username,options.password,options.authfile)

    if options.debug:
        s.setDebug(1)
    if options.id or options.server or options.facility or options.customer:
        action = ['list','namesearch','valuesearch','valuereplace','valueset','clone','addplatform','updateplatform']
        if arguments:
            if re.match('[Ll]ist$',arguments[0]):
                for i in s.getConfigurationRefs(options.id,options.regex):
                    try:
                        if s.isHPSA9x():
                            print "%s|%s" % (sacliutil.printObjectPath(s,[i]),sacliutil.printObjectID(i))
                        else:
                            print "%s|%s" % (i,sacliutil.printObjectID(i))
                    except SALib.AuthorizationDeniedException:
                        print "!!!%s is INACCESSIBLE!!!" % i
                        continue
                    except SALib.NotInFolder,i:
                        print "!!!%s is INACCESSIBLE!!!" % i
                        continue
            elif re.match('[Nn]amesearch',arguments[0]):
                if options.name:
                    if options.id:
                        configurationRefs = s.getConfigurationRefs(options.id,options.regex)
                        printConfigurableItems(s,configurationRefs,options.name,'name',options.regex)
                    elif options.server:
                        serverRefs = s.getServerRefs(options.server,options.regex)
                        printConfigurableItems(s,serverRefs,options.name,'name',options.regex)
                    elif options.customer:
                        serverRefs = s.getServerRefsByCustomer(options.customer,options.regex)
                        printConfigurableItems(s,serverRefs,options.name,'name',options.regex)
                    elif options.facility:
                        serverRefs = s.getServerRefsByFacility(options.facility,options.regex)
                        printConfigurableItems(s,serverRefs,options.name,'name',options.regex)
                    else:
                        p.print_help()
                        print "Please provide an id, server, customer, or facility option with --name"
                else:
                    p.print_help()
                    print "Please provide --name and either --id, --server, --customer,or --facility with namesearch action"
            elif re.match('[Vv]aluesearch',arguments[0]):
                if options.value:
                    if options.id:
                        configurationRefs = s.getConfigurationRefs(options.id,options.regex)
                        printConfigurableItems(s,configurationRefs,options.value,'value',options.regex)
                    elif options.server:
                        serverRefs = s.getServerRefs(options.server,options.regex)
                        printConfigurableItems(s,serverRefs,options.value,'value',options.regex)
                    elif options.customer:
                        serverRefs = s.getServerRefsByCustomer(options.customer,options.regex)
                        printConfigurableItems(s,serverRefs,options.value,'value',options.regex)
                    elif options.facility:
                        serverRefs = s.getServerRefsByFacility(options.facility,options.regex)
                        printConfigurableItems(s,serverRefs,options.value,'value',options.regex)
                else:
                    p.print_help()
                    print "Please provide --value and either --id, --server, --customer,or --facility with valuesearch action"
            elif re.match('[Vv]aluereplace',arguments[0]):
                if (options.name or options.matchstr) and options.value:
                    if options.id:
                        configurationRefs = s.getConfigurationRefs(options.id,options.regex)
                        if options.name:
                            configGenerator = s.findConfigurationParameter(configurationRefs,options.name,0,options.regex)
                        elif options.matchstr:
                            configGenerator = s.findConfigurationParameter(configurationRefs,options.matchstr,1,options.regex,False)
                    elif options.server:
                        serverRefs = s.getServerRefs(options.server,options.regex)
                        if options.name:
                            configGenerator = s.findConfigurationParameter(serverRefs,options.name,0,options.regex)
                        elif options.matchstr:
                            configGenerator = s.findConfigurationParameter(serverRefs,options.matchstr,1,options.regex,False)
                    elif options.customer:
                        serverRefs = s.getServerRefsByCustomer(options.customer,options.regex)
                        if options.name:
                            configGenerator = s.findConfigurationParameter(serverRefs,options.name,0,options.regex)
                        elif options.matchstr:
                            configGenerator = s.findConfigurationParameter(serverRefs,options.matchstr,1,options.regex,False)
                    elif options.facility:
                        serverRefs = s.getServerRefsByFacility(options.facility,options.regex)
                        if options.name:
                            configGenerator = s.findConfigurationParameter(serverRefs,options.name,0,options.regex)
                        elif options.matchstr:
                            configGenerator = s.findConfigurationParameter(serverRefs,options.matchstr,1,options.regex,False)
                    if options.dryrun:
                        if options.name:
                            for c in configGenerator:
                                for key in c.foundValuesetKeys:
                                    print "%s (Will NOT modify):" % c.configVO.ref
                                    print "BEFORE: %s = %s" % (key, c.configVO.valueset[key])
                                    print "AFTER: %s = %s\n" % (key, options.value)
                                for instance in c.instances:
                                    print "%s (Will NOT modify):" % c.configVO.instances[instance.index].ref
                                    for key in instance.foundValuesetKeys:
                                        print "BEFORE: %s = %s" % (key,c.configVO.instances[instance.index].valueset[key])
                                        print "AFTER: %s = %s\n" % (key,options.value)
                        elif options.matchstr:
                            for c in configGenerator:
                                for key in c.foundValuesetKeys:
                                    print "%s (Will NOT modify):" % c.configVO.ref
                                    print "BEFORE: %s = %s" % (key, c.configVO.valueset[key])
                                    print "AFTER: %s = %s\n" % (key,re.sub(options.matchstr, options.value, c.configVO.valueset[key])) 
                                for instance in c.instances:
                                    print "%s (Will NOT modify):" % c.configVO.instances[instance.index].ref
                                    for key in instance.foundValuesetKeys:
                                        print "BEFORE: %s = %s" % (key,c.configVO.instances[instance.index].valueset[key])
                                        print "AFTER: %s = %s\n" % (key,re.sub(options.matchstr, options.value, c.configVO.instances[instance.index].valueset[key]))
                    else:
                        if options.name:
                            replaceConfigGen = s.replaceConfigurationValue(configGenerator,options.value,options.scope,options.show,False,None)
                        elif options.matchstr:
                            replaceConfigGen = s.replaceConfigurationValue(configGenerator,options.value,options.scope,options.show,True,None)
                        for twistConfigItem in replaceConfigGen:
                            print "%s: Modified" % twistConfigItem.ref
                            if options.show:
                                print
                else:
                    p.print_help()
                    print "Please provide both --name=<name in valueset> and --value=<replacement value> with valuereplace action."
            elif re.match('[Vv]aluesets?',arguments[0]):
                if options.id:
                    configurationRefs = s.getConfigurationRefs(options.id,options.regex)
                    printConfigurableItems(s,configurationRefs,None,'all',options.regex)
                elif options.server:
                    serverRefs = s.getServerRefs(options.server,options.regex)
                    printConfigurableItems(s,serverRefs,None,'all',options.regex)
                elif options.customer:
                    serverRefs = s.getServerRefsByCustomer(options.customer,options.regex)
                    printConfigurableItems(s,serverRefs,None,'all',options.regex)
                elif options.facility:
                    serverRefs = s.getServerRefsByFacility(options.facility,options.regex)
                    printConfigurableItems(s,serverRefs,None,'all',options.regex)
            elif re.match('[Cc]lone',arguments[0]):
                if options.clonename:
                    configRef = s.cloneConfigurationRef(options.id,options.clonename)
                    if s.isHPSA9x():
                        print "created %s|ConfigurationRef:%d" % (sacliutil.printObjectPath(s,[configRef]),configRef.id)
                    else:
                        print "%s|%s" % (configRef,sacliutil.printObjectID(configRef))
            elif re.match('(?i)addplatform?',arguments[0]):
                if options.platform:
                    print "Adding platform on the following configurationVO(s):"
                    for configvo in s.addConfigurationPlatform(options.id,options.platform,options.regex):
                        print "%s" % configvo.ref
                else:
                    p.print_help()
                    print "You need to provide --platform=<platform name>."
            elif re.match('(?i)updateplatform?',arguments[0]):
                if options.platform:
                    print "Updating platform on the following configurationVO(s):"
                    for configvo in s.updateConfigurationPlatform(options.id,options.platform,options.regex):
                        print "%s" % configvo.ref
                else:
                    p.print_help()
                    print "You need to provide --platform=<platform name>."
            else:
                p.print_help()
                print "Provide an action: %s" % sacliutil.getActionList(action)
        else:
            p.print_help()
            print "Provide an action: %s" % sacliutil.getActionList(action)
Exemplo n.º 15
0
def main():
    p = sacliutil.standardOptions(
        "appconfig --id=<identifier> [--<modifier options>] [ <action> ]")
    p.add_option('--id', help="Specify identifier for appconfig.")
    p.add_option('--server', help="Specify server pattern for appconfig.")
    p.add_option('--name', help="Specifies name valueset of the appconfig.")
    p.add_option('--value', help="Specifies value valueset of the appconfig.")
    p.add_option('--matchstr',
                 help="search string for replacement by --value.")
    p.add_option('--clonename', help="Specifies appconfig clone name.")
    p.add_option('--customer', help="Specify servers by customer name.")
    p.add_option('--facility', help="Specifies servers by facility name.")
    p.add_option('--platform',
                 help="Specify platform by id, name, or pattern.")
    p.add_option(
        '--scope',
        default='all',
        help=
        "specify either appconfig,customer,facility,devicegroup,server,or all")
    p.add_option('--show',
                 action="store_true",
                 help="Show before and after valueset changes.")
    p.add_option('--dryrun',
                 action="store_true",
                 help="Do a dry run of valuereplace.")
    (options, arguments) = p.parse_args()
    s = sacliutil.getSALib(options.username, options.password,
                           options.authfile)

    if options.debug:
        s.setDebug(1)
    if options.id or options.server or options.facility or options.customer:
        action = [
            'list', 'namesearch', 'valuesearch', 'valuereplace', 'valueset',
            'clone', 'addplatform', 'updateplatform'
        ]
        if arguments:
            if re.match('[Ll]ist$', arguments[0]):
                for i in s.getConfigurationRefs(options.id, options.regex):
                    try:
                        if s.isHPSA9x():
                            print "%s|%s" % (sacliutil.printObjectPath(
                                s, [i]), sacliutil.printObjectID(i))
                        else:
                            print "%s|%s" % (i, sacliutil.printObjectID(i))
                    except SALib.AuthorizationDeniedException:
                        print "!!!%s is INACCESSIBLE!!!" % i
                        continue
                    except SALib.NotInFolder, i:
                        print "!!!%s is INACCESSIBLE!!!" % i
                        continue
            elif re.match('[Nn]amesearch', arguments[0]):
                if options.name:
                    if options.id:
                        configurationRefs = s.getConfigurationRefs(
                            options.id, options.regex)
                        printConfigurableItems(s, configurationRefs,
                                               options.name, 'name',
                                               options.regex)
                    elif options.server:
                        serverRefs = s.getServerRefs(options.server,
                                                     options.regex)
                        printConfigurableItems(s, serverRefs, options.name,
                                               'name', options.regex)
                    elif options.customer:
                        serverRefs = s.getServerRefsByCustomer(
                            options.customer, options.regex)
                        printConfigurableItems(s, serverRefs, options.name,
                                               'name', options.regex)
                    elif options.facility:
                        serverRefs = s.getServerRefsByFacility(
                            options.facility, options.regex)
                        printConfigurableItems(s, serverRefs, options.name,
                                               'name', options.regex)
                    else:
                        p.print_help()
                        print "Please provide an id, server, customer, or facility option with --name"
                else:
                    p.print_help()
                    print "Please provide --name and either --id, --server, --customer,or --facility with namesearch action"
            elif re.match('[Vv]aluesearch', arguments[0]):
                if options.value:
                    if options.id:
                        configurationRefs = s.getConfigurationRefs(
                            options.id, options.regex)
                        printConfigurableItems(s, configurationRefs,
                                               options.value, 'value',
                                               options.regex)
                    elif options.server:
                        serverRefs = s.getServerRefs(options.server,
                                                     options.regex)
                        printConfigurableItems(s, serverRefs, options.value,
                                               'value', options.regex)
                    elif options.customer:
                        serverRefs = s.getServerRefsByCustomer(
                            options.customer, options.regex)
                        printConfigurableItems(s, serverRefs, options.value,
                                               'value', options.regex)
                    elif options.facility:
                        serverRefs = s.getServerRefsByFacility(
                            options.facility, options.regex)
                        printConfigurableItems(s, serverRefs, options.value,
                                               'value', options.regex)
                else:
                    p.print_help()
                    print "Please provide --value and either --id, --server, --customer,or --facility with valuesearch action"
            elif re.match('[Vv]aluereplace', arguments[0]):
                if (options.name or options.matchstr) and options.value:
                    if options.id:
                        configurationRefs = s.getConfigurationRefs(
                            options.id, options.regex)
                        if options.name:
                            configGenerator = s.findConfigurationParameter(
                                configurationRefs, options.name, 0,
                                options.regex)
                        elif options.matchstr:
                            configGenerator = s.findConfigurationParameter(
                                configurationRefs, options.matchstr, 1,
                                options.regex, False)
                    elif options.server:
                        serverRefs = s.getServerRefs(options.server,
                                                     options.regex)
                        if options.name:
                            configGenerator = s.findConfigurationParameter(
                                serverRefs, options.name, 0, options.regex)
                        elif options.matchstr:
                            configGenerator = s.findConfigurationParameter(
                                serverRefs, options.matchstr, 1, options.regex,
                                False)
                    elif options.customer:
                        serverRefs = s.getServerRefsByCustomer(
                            options.customer, options.regex)
                        if options.name:
                            configGenerator = s.findConfigurationParameter(
                                serverRefs, options.name, 0, options.regex)
                        elif options.matchstr:
                            configGenerator = s.findConfigurationParameter(
                                serverRefs, options.matchstr, 1, options.regex,
                                False)
                    elif options.facility:
                        serverRefs = s.getServerRefsByFacility(
                            options.facility, options.regex)
                        if options.name:
                            configGenerator = s.findConfigurationParameter(
                                serverRefs, options.name, 0, options.regex)
                        elif options.matchstr:
                            configGenerator = s.findConfigurationParameter(
                                serverRefs, options.matchstr, 1, options.regex,
                                False)
                    if options.dryrun:
                        if options.name:
                            for c in configGenerator:
                                for key in c.foundValuesetKeys:
                                    print "%s (Will NOT modify):" % c.configVO.ref
                                    print "BEFORE: %s = %s" % (
                                        key, c.configVO.valueset[key])
                                    print "AFTER: %s = %s\n" % (key,
                                                                options.value)
                                for instance in c.instances:
                                    print "%s (Will NOT modify):" % c.configVO.instances[
                                        instance.index].ref
                                    for key in instance.foundValuesetKeys:
                                        print "BEFORE: %s = %s" % (
                                            key, c.configVO.instances[
                                                instance.index].valueset[key])
                                        print "AFTER: %s = %s\n" % (
                                            key, options.value)
                        elif options.matchstr:
                            for c in configGenerator:
                                for key in c.foundValuesetKeys:
                                    print "%s (Will NOT modify):" % c.configVO.ref
                                    print "BEFORE: %s = %s" % (
                                        key, c.configVO.valueset[key])
                                    print "AFTER: %s = %s\n" % (
                                        key,
                                        re.sub(options.matchstr, options.value,
                                               c.configVO.valueset[key]))
                                for instance in c.instances:
                                    print "%s (Will NOT modify):" % c.configVO.instances[
                                        instance.index].ref
                                    for key in instance.foundValuesetKeys:
                                        print "BEFORE: %s = %s" % (
                                            key, c.configVO.instances[
                                                instance.index].valueset[key])
                                        print "AFTER: %s = %s\n" % (
                                            key,
                                            re.sub(
                                                options.matchstr,
                                                options.value, c.configVO.
                                                instances[instance.index].
                                                valueset[key]))
                    else:
                        if options.name:
                            replaceConfigGen = s.replaceConfigurationValue(
                                configGenerator, options.value, options.scope,
                                options.show, False, None)
                        elif options.matchstr:
                            replaceConfigGen = s.replaceConfigurationValue(
                                configGenerator, options.value, options.scope,
                                options.show, True, None)
                        for twistConfigItem in replaceConfigGen:
                            print "%s: Modified" % twistConfigItem.ref
                            if options.show:
                                print
                else:
                    p.print_help()
                    print "Please provide both --name=<name in valueset> and --value=<replacement value> with valuereplace action."
            elif re.match('[Vv]aluesets?', arguments[0]):
                if options.id:
                    configurationRefs = s.getConfigurationRefs(
                        options.id, options.regex)
                    printConfigurableItems(s, configurationRefs, None, 'all',
                                           options.regex)
                elif options.server:
                    serverRefs = s.getServerRefs(options.server, options.regex)
                    printConfigurableItems(s, serverRefs, None, 'all',
                                           options.regex)
                elif options.customer:
                    serverRefs = s.getServerRefsByCustomer(
                        options.customer, options.regex)
                    printConfigurableItems(s, serverRefs, None, 'all',
                                           options.regex)
                elif options.facility:
                    serverRefs = s.getServerRefsByFacility(
                        options.facility, options.regex)
                    printConfigurableItems(s, serverRefs, None, 'all',
                                           options.regex)
            elif re.match('[Cc]lone', arguments[0]):
                if options.clonename:
                    configRef = s.cloneConfigurationRef(
                        options.id, options.clonename)
                    if s.isHPSA9x():
                        print "created %s|ConfigurationRef:%d" % (
                            sacliutil.printObjectPath(
                                s, [configRef]), configRef.id)
                    else:
                        print "%s|%s" % (configRef,
                                         sacliutil.printObjectID(configRef))
            elif re.match('(?i)addplatform?', arguments[0]):
                if options.platform:
                    print "Adding platform on the following configurationVO(s):"
                    for configvo in s.addConfigurationPlatform(
                            options.id, options.platform, options.regex):
                        print "%s" % configvo.ref
                else:
                    p.print_help()
                    print "You need to provide --platform=<platform name>."
            elif re.match('(?i)updateplatform?', arguments[0]):
                if options.platform:
                    print "Updating platform on the following configurationVO(s):"
                    for configvo in s.updateConfigurationPlatform(
                            options.id, options.platform, options.regex):
                        print "%s" % configvo.ref
                else:
                    p.print_help()
                    print "You need to provide --platform=<platform name>."
            else:
                p.print_help()
                print "Provide an action: %s" % sacliutil.getActionList(action)
        else:
            p.print_help()
            print "Provide an action: %s" % sacliutil.getActionList(action)
Exemplo n.º 16
0
def main():
    p = sacliutil.standardOptions(
        "servergroup (--id=<device group identifier>|--new=<device group name or path>) [modifiers] <action>"
    )
    p.add_option(
        '--id',
        help=
        "use with action info,listall,listgroup,remove,list,listregex,addservers,removeservers,listdevice"
    )
    p.add_option('--new', help="")
    p.add_option('--devices', help="")
    p.add_option('--expression', help="")
    p.add_option('--empty', action="store_true", help="")
    (options, arguments) = p.parse_args()
    s = sacliutil.getSALib(options.username, options.password,
                           options.authfile)
    if options.debug:
        s.setDebug(1)
    if options.id:
        action = [
            'info', 'listall', 'listgroup', 'remove', 'list', 'listregex',
            'addservers', 'removeservers', 'listdevice'
        ]
        if arguments:
            if arguments[0] == 'info':
                print "Server Group Name: %s" % (options.id, )
                sacliutil.print_servergroupinfo(s, 's.getServerGroupInfo',
                                                options.id)
            elif re.match('[Ll]istdevices?', arguments[0]):
                for i in s.getServerGroupInfo(options.id)['devices']:
                    print "%s" % i
            elif re.match('[Ll]istgroups?', arguments[0]):
                for i in s.getServerGroupInfo(options.id)['children']:
                    print "%s" % i
            elif re.match('[Rr]emove', arguments[0]):
                s.removeServerGroup(options.id)
            elif re.match('[Aa]ddservers?', arguments[0]):
                if options.devices:
                    s.addServersToServerGroup(options.devices, options.id)
                else:
                    print "ERROR: Need to specify the devices to add with --devices=<server names,>"
                    sys.exit(1)
            elif re.match('[Rr]emoveservers?', arguments[0]):
                if options.devices:
                    s.removeServersFromServerGroup(options.devices, options.id)
                else:
                    print "ERROR: Need to specify the devices to remove with --devices=<server names,>"
                    sys.exit(1)
            elif re.match('[Ll]ist', arguments[0]):
                if re.match('[Ll]istall', arguments[0]):
                    for i in list(
                            s.getServerGroupInfo(options.id)['children']):
                        print "%s" % i
                    for i in list(s.getServerGroupInfo(options.id)['devices']):
                        print "%s" % i
                else:
                    for i in s.getDeviceGroupRefs(options.id):
                        dvcGroupVO = s.callUAPI('device.DeviceGroupService',
                                                'getDeviceGroupVO', i)
                        print "%s (DeviceGroupRef: %d)" % (re.sub(
                            '^Device Groups', '', dvcGroupVO.fullName), i.id)
            elif re.match('[Rr]egexlist', arguments[0]):
                for i in s.getDeviceGroupRefs(options.id, True):
                    dvcGroupVO = s.callUAPI('device.DeviceGroupService',
                                            'getDeviceGroupVO', i)
                    print "%s (DeviceGroupRef: %d)" % (re.sub(
                        '^Device Groups', '', dvcGroupVO.fullName), i.id)
            else:
                p.print_help()
                print "With --id=<device group identifier> you need to provide an action: %s" % \
                                                                    sacliutil.getActionList(action)
        else:
            p.print_help()
            print "With --id=<device group identifier> you need to provide an action: %s" % \
                                                                sacliutil.getActionList(action)
    elif options.new:
        action = ['create']
        if arguments:
            if re.match('[Cc]reate', arguments[0]):
                if options.devices:
                    if options.expression:
                        print "You can't add device(s) to a dynamic group. Using the expression option implies that this is a dynamic group."
                    else:
                        s.createServerGroup(options.new, options.devices)
                elif options.expression:
                    s.createServerGroup(options.new,
                                        isDynamic=True,
                                        ruleExpression=options.expression)
                elif options.empty:
                    s.createServerGroup(options.new, dvc_list=[])
                else:
                    p.print_help()
                    print "Please specify --devices,--expression,or --empty to create either a static group, a dynamic group, or an empty server group respectively."
            else:
                p.print_help()
                print "Please provide create action with --new."
        else:
            p.print_help()
            print "With --new=<new device group or device group path> you need to provide an action: %s" % \
                                                                sacliutil.getActionList(action)
    else:
        p.print_help()
Exemplo n.º 17
0
def main():
    p = sacliutil.standardOptions("package --id=<identifier> [--<modifier options>] [ <action> ]")
    p.add_option('--id', help="Specify a identifier which is an Opsware ID, software policy name, or folder path and software policy name.")
    p.add_option('--platform', help="Use with upload action.")
    p.add_option('--pkgtype', help="Use with upload action.")
    p.add_option('--folder', help="Use with package upload.")
    p.add_option('--platform', help="Use with package upload.")
    p.add_option('--pkgfile', help="Use with upload or download action.")
    p.add_option('--pkgreplace', help="Use with overwrite action.")
    p.add_option('--pkgtypes', action="store_true", help="List package types.")
    p.add_option('--name', help="name to specify when calling update package attribute.")
    p.add_option('--value', help="value to specify when calling update package attribute.")
    (options,arguments) = p.parse_args()
    s = sacliutil.getSALib(options.username,options.password,options.authfile)

    if options.debug:
        s.setDebug(1)
    try:
        if options.id:
            action = ['list','download','update','info','overwrite','addplatform','updateplatform']
            if arguments:
                if re.match('[Ll]ist',arguments[0]):
                    if options.regex:
                        unitRefsList = s.getUnitRefs(options.id,True)
                    else:
                        unitRefsList = s.getUnitRefs(options.id)
                    for i in unitRefsList:
                        try:
                            print "%s|%s" % (sacliutil.printObjectPath(s,[i]),sacliutil.printObjectID(i))
                        except SALib.NotInFolder,args:
                            print "Package %s is not accessible in HP SA folders. Check old package repository structure. (i.e. pre HP SA 7.x) " % args
                            continue
                elif re.match('[Ii]nfo',arguments[0]):
                    for i in s.getUnitRefs(options.id):
                        print "SA Unit ---- %s ----" % i.name
                        sacliutil.print_unitinfo(s,'s.getUnitInfo',i)
                        print
                elif re.match('[Dd]ownload',arguments[0]):
                    if options.regex:
                        s.downloadUnit(options.id,options.pkgfile,options.regex)
                    else:
                        s.downloadUnit(options.id,options.pkgfile)
                elif re.match('(?i)^update$',arguments[0]):
                    if options.name and options.value:
                        value = sacliutil.getSAObjectRefsOrString(s,options.value)
                        unitId = s.updateUnitVO(options.id,options.name,value)
                        if isinstance(unitId,list):
                            print "Updated Unit ID: %s|%s" % (sacliutil.printObjectPath(s,unitId.ref),sacliutil.printObjectID(unitId.ref[0]))
                        else:
                            print "Updated Unit ID: %s|%s" % (sacliutil.printObjectPath(s,[unitId.ref]),sacliutil.printObjectID(unitId.ref))
                    else:
                        p.print_help()
                        print "With update action provide --name=<name of attribute> and --value=<value of attribute> options."
                elif re.match('(?i)updateplatform?',arguments[0]):
                    if options.platform:
                        print "Updating platform on the following packages:"
                        for unitvo in s.updateUnitPlatform(options.id,options.platform,options.regex):
                            print "%s" % unitvo.ref
                    else:
                        p.print_help()
                        print "You need to provide --platform=<platform name>."
                elif re.match('(?i)addplatform?',arguments[0]):
                    if options.platform:
                        print "Adding platform to the following packages:"
                        for unitvo in s.addUnitPlatform(options.id,options.platform,options.regex):
                            print "%s" % unitvo.ref
                    else:
                        p.print_help()
                        print "You need to provide --platform=<platform name>."
                elif re.match('[Oo]verwrite',arguments[0]):
                    if options.pkgtype:
                        filetype = options.pkgtype
                    else:
                        filetype = sacliutil.detectPkgType(options.pkgfile)
                    if options.id and options.platform and filetype:
                        unitId = s.replaceUnit(options.pkgfile,filetype,options.id,options.platform)
                        print "Overwrote Unit: %s|%s" % (sacliutil.printObjectPath(s,[unitId]),sacliutil.printObjectID([unitId]))
                    else:
                        if not options.platform:
                            p.print_help()
                            print "You need to provide --platform with action overwrite"
                        elif not options.id:
                            p.print_help()
                            print "You need to provide --id with action overwrite"
                        elif not filetype:
                            p.print_help()
                            print "--pkgtype wasn't given and package couldn't detect the file type for %s" % options.pkgfile
                else:
                    p.print_help()
                    print "With --id provide the following actions: %s" % sacliutil.getActionList(action)
            else:
                p.print_help()
                print "With --id provide the following actions: %s" % sacliutil.getActionList(action)
        elif options.pkgfile:
            action = ['upload']
            if arguments:
                if re.match('[Uu]pload',arguments[0]):
                    filelist = glob.glob(options.pkgfile)
                    for filei in filelist:
                        if options.pkgtype:
                            filetype = options.pkgtype
                        else:
                            filetype = sacliutil.detectPkgType(filei)
                        if filetype and options.platform and options.folder:
                            if options.debug:
                                print "package type: %s" % filetype
                            if options.regex:
                                unitId = s.uploadUnit(filei,filetype,options.platform,options.folder,options.regex)
                            else:
                                unitId = s.uploadUnit(filei,filetype,options.platform,options.folder)
                            print "Created Unit: %s|%s" % (sacliutil.printObjectPath(s,[unitId]),sacliutil.printObjectID([unitId]))
                        else:
                            if not options.platform:
                                p.print_help()
                                print "You need to provide --platform with action upload."
                            elif not options.folder:
                                p.print_help()
                                print "You need to provide --folder with action upload."
                            elif not filetype:
                                p.print_help()
                                print "--pkgtype wasn't given and package couldn't detect the file type for %s" % filei
                else:
                    p.print_help()
                    print "Please provide an action: %s" % sacliutil.getActionList(action)
            else:
                p.print_help()
                print "Please provide an action: %s" % sacliutil.getActionList(action)
Exemplo n.º 18
0
def main():
    p = sacliutil.standardOptions("server --id=<identifier> [--<modifier options>] [ <action> ]")
    p.add_option('--id', help="")
    p.add_option('--serverscript', help="Use to run a server script.")
    p.add_option('--customfield', help="Use to list or set a customfield.")
    p.add_option('--attribute', help="Use to set a server attribute, use info action to see attribute.")
    p.add_option('--value', help="Use to set a customfield value.")
    p.add_option('--days', help="Use to specify number of days to go back when viewing server history.")
    p.add_option('--weeks', help="Use to specify number of weeks to go back when viewing server history.")
    p.add_option('--dvcid',action="store_true", help="Use to view device id.")
    p.add_option('--customer',help="Specify a servers belonging to a facility.")
    p.add_option('--newcustomer',help="Use to assign servers to a new customer name/id. Used with assign action.")
    p.add_option('--facility',help="Specify a group of servers belonging to a facility.")
    p.add_option('--spolicy',help="Specify a software policy name for servers attached to them.")
    p.add_option('--servername', help="new server name, use with rename.")
    p.add_option('--sgmembers', help="list out servers that belong to a device group.")
    p.add_option('--caname', help="Use with server setca (Set Custom Attribute)")
    p.add_option('--value', help="Use with server setca (Set Custom Attribute)")
    (options,arguments) = p.parse_args()
    s = sacliutil.getSALib(options.username,options.password,options.authfile)

    if options.debug:
        s.setDebug(1)
    if options.id or options.facility or options.customer or options.spolicy or options.sgmembers:
        action = ['info','policystatus','list','history','updatecustomfield','showcustomfields','assign','getca','setca','clean','rename','commtest']
        if options.id and not (options.facility or options.customer or options.spolicy or options.sgmembers):
            serverRefs = s.getServerRefs(options.id,options.regex)
        elif options.facility and not (options.id or options.customer or options.spolicy or options.sgmembers):
            serverRefs = s.getServerRefsByFacility(options.facility,options.regex)
        elif options.customer and not (options.id or options.facility or options.spolicy or options.sgmembers):
            serverRefs = s.getServerRefsByCustomer(options.customer,options.regex)
        elif options.spolicy and not (options.id or options.facility or options.customer or options.sgmembers):
            serverRefs = []
            for spolicy,serverlist in s.getServerRefsBySoftwarePolicy(options.spolicy,options.regex).iteritems():
                serverRefs = serverRefs + serverlist
        elif options.sgmembers and not (options.id or options.facility or options.customer or options.spolicy):
            serverRefs = s.getServerGroupInfo(options.sgmembers,options.regex)['devices']
        else:
            print "Incorrect options given, possibly incorrect combination or the options don't exist."
            p.print_help()
        try:
            if arguments:
                # if arguments[0] == 'info':
                if re.match('[Ii]nfo',arguments[0]):
                    for i in serverRefs:
                        print "ServerRef: %s" % i
                        sacliutil.print_serverinfo(s,'s.getServerInfo',i)
                        print
                elif re.match('[Pp]olicystatus',arguments[0]):
                    policyStates = s.getPolicyAttachableStatesByServerRefs(serverRefs)
                    for sref in serverRefs:
                        print "ServerRef: %s" % sref
                        for policystate in policyStates:
                            if sref.id == policystate.policyAttachable.id:
                                policy = policystate.policyAssociation.policy
                                direct = policystate.policyAssociation.direct
                                remediated = policystate.policyAssociation.remediated
                                attached = policystate.policyAssociation.attached
                                dvcgroup = policystate.policyAssociation.deviceGroups
                                print "policy:%s direct:%s remediated:%s attached:%s dvcgroup:%s" % (policy,direct,remediated,attached,dvcgroup)
                        print
                elif re.match('(?i)list$',arguments[0]):
                    for i in serverRefs:
                        print "%s" % i
                elif re.match('(?i)history$',arguments[0]):
                    if options.days:
                        for i in serverRefs:
                            print "Server Name: %s" % i.name
                            for j in s.getServerHistorybyDays(i,string.atol(options.days)):
                                print "%s" % re.sub('[{}]','',"%s" % j)
                        #print "%s" % options.days
                        print
                    elif options.weeks:
                        for i in serverRefs:
                            print "Server Name: %s" % i.name
                            for j in s.getServerHistorybyWeeks(i,string.atol(options.weeks)):
                                print "%s" % re.sub('[{}]','',"%s" % j)
                        print
                    else:
                        p.print_help()
                        print "With [--days=<num of days> or --weeks=<num of weeks]"
                elif re.match('(?i)updatecustomfields?',arguments[0]):
                    if options.customfield:
                        results = s.setServerCustomFieldsByServerRefs(serverRefs,options.customfield,options.value,options.regex)
                        serverKeys = results.keys()
                        serverKeys.sort()
                        for server in serverKeys:
                            cfKeys = results[server].keys()
                            cfKeys.sort()
                            cfs = results[server]
                            for cf in cfKeys:
                                print "updated %s -> %s: oldvalue=%s newvalue=%s" % (server,cf,cfs[cf]['oldvalue'],cfs[cf]['newvalue'])  
                    else:
                        print "Must provide --customfield and --value option."
                elif re.match('(?i)updateattribute?',arguments[0]):
                    if options.attribute and options.value:
                        print "updated servers:"
                        for updated_svo in s.setServerAttributeByServerRefs(serverRefs,options.attribute,options.value,options.regex):
                            print "%s" % (updated_svo.ref)  
                    else:
                        print "Must provide --attribute and --value option."
                elif re.match('(?i)showcustomfields?',arguments[0]):
                    serverCustomFields = s.getServerCustomFieldsByServerRefs(serverRefs,options.customfield,regex=options.regex)
                    for server in serverCustomFields.keys():
                        print "%s" % server
                        for customfield in serverCustomFields[server]:
                            key = customfield.iterkeys().next()
                            print "%s: %s" % (key,customfield[key])
                        print
                elif re.match('(?i)assign',arguments[0]):
                    if options.newcustomer:
                        customer_ref = s.getCustomerRefs(options.newcustomer, options.regex)
                        if len(customer_ref) < 1:
                            p.print_help()
                            print "No Customer found."
                        elif len(customer_ref) > 1:
                            p.print_help()
                            print "Multiple Customers found, only one can be specified."
                        else:
                            serverGenerator = s.assignCustomerToServerByServerRefs(serverRefs,options.newcustomer,options.regex)
                            for server in serverGenerator:
                                print "%s assigned to customer %s" % server # server is a tuple returned by serverGenerator...
                    else:
                        print "Must provide --newcustomer with action assign."
                        p.print_help()
                elif re.match('(?i)getca?',arguments[0]):
                    servercas = s.getCustomAttributesOnServerByServerRefs(serverRefs)
                    for serverca in servercas.keys():
                        print "%s" % serverca
                        for ca in servercas[serverca].keys():
                            if not re.match('^__OPSW.*',ca):
                                print "%s : %s" % (ca,servercas[serverca][ca])
                        print
                elif re.match('(?i)setca?',arguments[0]):
                    if options.caname:
                        serverlist = s.setCustomAttributesOnServerByServerRefs(serverRefs,options.caname,options.value)
                        print "Updated Server CA:"
                        for server in serverlist:
                            print "%s" % server
                        print
                    else:
                        p.print_help()
                        print "You need to either provide --caname=<name> and --value=value with action setca."
                elif re.match('(?i)clean$',arguments[0]):
                    print "Cleaning server name (i.e. striping whitespace before and after the name.):"
                    for servervo in s.getServerValueObjectsByServerRefs(serverRefs,options.regex):
                        servervo.name = servervo.name.strip()
                        print "%s" % s.updateServerVO(servervo).ref
                elif re.match('(?i)rename$',arguments[0]):
                    if len(serverRefs) < 1:
                        raise SALib.NoObjectRefFound,options.id
                    elif len(serverRefs) > 1:
                        raise SALib.MultipleObjectRefsFound,options.server
                    servervo = s.getServerValueObjectsByServerRefs(serverRefs,options.regex)[0]
                    servervo.name = options.servername
                    print "Renamed %s to %s" % (serverRefs[0].name,s.updateServerVO(servervo).ref.name)
                elif re.match('(?i)commtest$',arguments[0]):
                    print "%s" % s.serverCommTest(serverRefs)
                else:
                    p.print_help()
                    print "Provide the action: %s" % sacliutil.getActionList(action)
            else:
                p.print_help()
                print "Provide the action: %s" % sacliutil.getActionList(action)
        except SALib.NoServerRefFound,sref:
            print "ERROR: Couldn't find %s." % sref
        except SALib.MultipleServerRefsFound,sref:
            print "ERROR: Multiple Servers found: %s, specify only one server for this operation." % sref
Exemplo n.º 19
0
def main():
    p = sacliutil.standardOptions("servergroup (--id=<device group identifier>|--new=<device group name or path>) [modifiers] <action>")
    p.add_option('--id', help="use with action info,listall,listgroup,remove,list,listregex,addservers,removeservers,listdevice")
    p.add_option('--new', help="")
    p.add_option('--devices', help="")
    p.add_option('--expression', help="")
    p.add_option('--empty',action="store_true",help="")
    (options,arguments) = p.parse_args()
    s = sacliutil.getSALib(options.username,options.password,options.authfile)
    if options.debug:
        s.setDebug(1)
    if options.id:
        action = ['info','listall','listgroup','remove','list','listregex','addservers','removeservers','listdevice']
        if arguments:
            if arguments[0] == 'info':
                print "Server Group Name: %s" % (options.id,)
                sacliutil.print_servergroupinfo(s,'s.getServerGroupInfo',options.id)
            elif re.match('[Ll]istdevices?',arguments[0]):
                for i in s.getServerGroupInfo(options.id)['devices']:
                    print "%s" % i
            elif re.match('[Ll]istgroups?',arguments[0]):
                for i in s.getServerGroupInfo(options.id)['children']:
                    print "%s" % i
            elif re.match('[Rr]emove',arguments[0]):
                s.removeServerGroup(options.id)
            elif re.match('[Aa]ddservers?',arguments[0]):
                if options.devices:
                    s.addServersToServerGroup(options.devices,options.id)
                else:
                    print "ERROR: Need to specify the devices to add with --devices=<server names,>"
                    sys.exit(1)
            elif re.match('[Rr]emoveservers?',arguments[0]):
                if options.devices:
                    s.removeServersFromServerGroup(options.devices,options.id)
                else:
                    print "ERROR: Need to specify the devices to remove with --devices=<server names,>"
                    sys.exit(1)
            elif re.match('[Ll]ist',arguments[0]):
                if re.match('[Ll]istall',arguments[0]):
                    for i in list(s.getServerGroupInfo(options.id)['children']): print "%s" % i
                    for i in list(s.getServerGroupInfo(options.id)['devices']): print "%s" % i
                else:
                    for i in s.getDeviceGroupRefs(options.id):
                        dvcGroupVO = s.callUAPI('device.DeviceGroupService','getDeviceGroupVO',i)
                        print "%s (DeviceGroupRef: %d)" % (re.sub('^Device Groups','',dvcGroupVO.fullName),i.id)
            elif re.match('[Rr]egexlist',arguments[0]):
                for i in s.getDeviceGroupRefs(options.id,True):
                    dvcGroupVO = s.callUAPI('device.DeviceGroupService','getDeviceGroupVO',i)
                    print "%s (DeviceGroupRef: %d)" % (re.sub('^Device Groups','',dvcGroupVO.fullName),i.id)
            else:
                p.print_help()
                print "With --id=<device group identifier> you need to provide an action: %s" % \
                                                                    sacliutil.getActionList(action)
        else:
            p.print_help()
            print "With --id=<device group identifier> you need to provide an action: %s" % \
                                                                sacliutil.getActionList(action)
    elif options.new:
        action = ['create']
        if arguments:
            if re.match('[Cc]reate',arguments[0]):
                if options.devices:
                    if options.expression:
                        print "You can't add device(s) to a dynamic group. Using the expression option implies that this is a dynamic group."
                    else:
                        s.createServerGroup(options.new,options.devices)
                elif options.expression:
                    s.createServerGroup(options.new,isDynamic=True,ruleExpression=options.expression)
                elif options.empty:
                    s.createServerGroup(options.new,dvc_list=[])
                else:
                    p.print_help()
                    print "Please specify --devices,--expression,or --empty to create either a static group, a dynamic group, or an empty server group respectively."
            else:
                p.print_help()
                print "Please provide create action with --new."
        else:
            p.print_help()
            print "With --new=<new device group or device group path> you need to provide an action: %s" % \
                                                                sacliutil.getActionList(action)
    else:
        p.print_help()
Exemplo n.º 20
0
def main():
    p = sacliutil.standardOptions("")
    p.add_option('--id', help="Specify ID or OGFS Script name.")
    p.add_option('--notification', action="store_true",help="Emails notification to the user.")
    p.add_option('--args', help="Arguments to pass to the OGFS Script.", default="")
    p.add_option('--exe', help="Interpreter or shell to use, by default /bin/bash", default="/bin/bash")
    p.add_option('--workingdir', help="Working directory of the OGFS Script.")
    p.add_option('--version', help="Version Label for OGFS Script.")
    (options,arguments) = p.parse_args()
    s = sacliutil.getSALib(options.username,options.password,options.authfile)

    if options.debug:
        s.setDebug(1)
    if options.id:
        action = ['wayrun','list','run','print']
        if arguments:
            if re.match('[Ww]ayrun',arguments[0]):
                if options.args:
                    args = options.args
                else:
                    args = ''
                jobid = s.runOGFSScript(options.id,args,options.notification,options.workingdir)
                print "%s" % jobid
            elif re.match('[Rr]un',arguments[0]):
                #result = subprocess.Popen(args=s.getOGFSScriptSource(options.id,options.version),shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
                ogfs_ref = s.getOGFSScriptRefs(options.id, options.regex)
                if len(ogfs_ref) > 1:
                    raise SALib.MultipleOGFSScriptFound,ogfs_ref
                script_path = "/tmp/%s-ogfsscript-%s" % (s._SALib__username, ogfs_ref[0].id)
                fd = open( script_path, "w+")
                fd.write(s.getOGFSScriptSource(options.id,options.version))
                fd.close()
                os.chmod( script_path, 0700 )
                args = [ ]
                if options.exe:
                    args.append(options.exe)
                args = args + [ script_path ] + shlex.split(options.args)
                ret = subprocess.call(args)
                sys.exit(ret)
                #print "%s" % result.stdout.read()
                #stdErr = result.stderr.read()
                #if stdErr:
                #    print "%s" % stdErr
            elif re.match('[p]rint',arguments[0]):
                print "%s" % s.getOGFSScriptSource(options.id,options.version)
            elif re.match('[Ll]ist',arguments[0]):
                OGFSScriptRefs = s.getOGFSScriptRefs(options.id,options.regex)
                for i in OGFSScriptRefs:
                    try:
                        pathDict = s.getObjectPath([ i ],False) 
                        (parentPath,SP) = os.path.split(pathDict[i])
                        if parentPath == "/":
                            print "%s%s" % (parentPath,i)
                        else:
                            print "%s/%s" % (parentPath,i)
                    except SALib.AuthorizationDeniedException:
                        print "!!!%s is INACCESSIBLE!!!" % i
                        continue
                    except SALib.NotInFolderException:
                        print "!!!%s is INACCESSIBLE!!!" % i
                        continue
            else:
                p.print_help()
                print "Please provide an action: %s" % sacliutil.getActionList(action)
        else:
            p.print_help()
            print "Please provide an action: %s" % sacliutil.getActionList(action)
    else:
        p.print_help()
Exemplo n.º 21
0
def main():
    p = sacliutil.standardOptions("serverscript --id=<identifier> [--<modifier options>] [ <action> ]")
    p.add_option('--id', help="Specify server script name, id, or folder path and server script name")
    p.add_option('--server', help="Specify server name or id")
    p.add_option('--servergroup', help="Specify server group by id or path.")
    p.add_option('--spolicy', help="Specify servers by software policy associations.")
    p.add_option('--customer', help="Specify servers by customer associations.")
    p.add_option('--facility', help="Specify servers by facility associations.")
    p.add_option('--file', help="Specify script filename.")
    p.add_option('--folder', help="Specify folder by id or path that script will be stored in.")
    p.add_option('--type', help="Specify the script extension sh, ps1, bat, or vbs (unix shell, powershell, batch, or visual basic script respectively.)")
    p.add_option('--args', default='', help="Specify arguments that need to be passed to the script.")
    p.add_option('--timeout', default='300', help="Specify timeout for the server script. Default is 300 seconds")
    p.add_option('--scriptname', default='', help="Use this as name instead of the filename for the server script. Default is to use the filename for the server script name.")
    p.add_option('--description', default='', help="Use given description instead of the filename for the server script. Default is to set filename for description.")
    p.add_option('--versionlabel', default='', help="Specify version label for the server script.")
    p.add_option('--nosuperuser',default=True, action="store_false",help="Specify whether this script run as a super user or not. Default is set to True.")
    p.add_option('--email',default=False,action="store_true",help="Email using SA account information. Default is set to False")
    p.add_option('--noserverchange',default=True, action="store_false",help="Specify whether this script can make changes to the server or not. Default is set to True")
    (options,arguments) = p.parse_args()
    s = sacliutil.getSALib(options.username,options.password,options.authfile)

    if options.debug:
        s.setDebug(1)
    if options.id:
        action = ['info','list','run']
        if arguments:
            if re.match('[Ii]nfo',arguments[0]):
                for i in s.getServerScriptRefs(options.id,options.regex):
                    print "Server Script: %s" % i.name
                    sacliutil.print_serverscriptinfo(s,'s.getServerScriptInfo',i)
                    folderdict = s.getServerScriptInfo(i)
                    print "location: %s" % s.getObjectPath( [ folderdict['folder'] ])
                    print "source: \n%s" % s.showServerScriptSource(i)
            elif re.match('(?i)list?',arguments[0]):
                serverScriptRefs = s.getServerScriptRefs(options.id,options.regex)
                for i in serverScriptRefs:
                    try:
                        pathDict = s.getObjectPath([ i ],False) 
                        (parentPath,SP) = os.path.split(pathDict[i])
                        if parentPath == "/":
                            print "%s%s" % (parentPath,i)
                        else:
                            print "%s/%s" % (parentPath,i)
                    except SALib.AuthorizationDeniedException:
                        print "!!!%s is INACCESSIBLE!!!" % i
                        continue
                    except SALib.NotInFolderException:
                        print "!!!%s is INACCESSIBLE!!!" % i
                        continue
            elif re.match('(?i)^run$',arguments[0]):
                if options.id and (options.server or options.servergroup or options.spolicy or options.customer or options.facility or options.sgmembers):
                    jobId = None
                    if options.server and not (options.servergroup or options.spolicy or options.customer or options.facility):
                        serverRefs = s.getServerRefs(options.server,options.regex)
                        jobId = s.runServerScript(options.id,serverRefs,options.args,None,string.atoi(options.timeout),options.email,options.regex)
                    elif options.spolicy and not (options.server or options.servergroup or options.customer or options.facility):
                        serverRefs = []
                        for spolicy,serverlist in s.getServerRefsBySoftwarePolicy(options.spolicy,options.regex).iteritems():
                            serverRefs = serverRefs + serverlist
                        jobId = s.runServerScript(options.id,serverRefs,options.args,None,string.atoi(options.timeout),options.email,options.regex)
                    elif options.servergroup and not (options.server or options.spolicy or options.customer or options.facility):
                        deviceGroupRefs = s.getDeviceGroupRefs(options.servergroup,options.regex)
                        jobId = s.runServerScript(options.id,deviceGroupRefs,options.args,None,string.atoi(options.timeout),options.email,options.regex)
                    elif options.customer and not (options.server or options.servergroup or options.spolicy or options.facility):
                        serverRefs = s.getServerRefsByCustomer(options.customer,options.regex)
                        jobId = s.runServerScript(options.id,serverRefs,options.args,None,string.atoi(options.timeout),options.email,options.regex)
                    elif options.facility and not (options.server or options.servergroup or options.spolicy or options.customer):
                        serverRefs = s.getServerRefsByFacility(options.facility,options.regex)
                        jobId = s.runServerScript(options.id,serverRefs,options.args,None,string.atoi(options.timeout),options.email,options.regex)
                    else:
                        p.print_help()
                        print "Please provide --id=<Server script> and one of (--server,--servergroup,--spolicy,--customer, or--facility) and --type=<SH,PS1,BAT,VBS> with run action"
                    if jobId:
                        print "JobID: %s" % jobId
                else:
                    p.print_help()
                    print "Please provide --id=<SA Server script> and --server=<Server ID or Name>/--servergroup <servergroup id or name> with run action"
            else:
                p.print_help()
                print "Please provide an action: %s" % sacliutil.getActionList(action)
        else:
            p.print_help()
            print "Please provide an action: %s" % sacliutil.getActionList(action)
    elif options.file:
        action = ['runadhoc','create']
        if arguments:
            if re.match('(?i)^runadhoc$',arguments[0]):
#                if options.servergroup and options.server:
#                    p.print_help()
#                    raise bothSgroupAndServer
                if options.file and (options.server or options.servergroup or options.spolicy or options.customer or options.facility) and options.type:
                    jobId = None
                    if re.match('(?i)sh',options.type):
                        codeType = 'SH'
                    elif re.match('(?i)ps1',options.type):
                        codeType = 'PS1'
                    elif re.match('(?i)bat',options.type):
                        codeType = 'BAT'
                    elif re.match('(?i)vbs',options.type):
                        codeType = 'VBS'
                    else:
                        print "--type %s doesn't match sh, ps1, bat, or vbs" % options.type
                        sys.exit(1)
                    if options.server and not (options.servergroup or options.spolicy or options.customer or options.facility):
                        serverRefs = s.getServerRefs(options.server,options.regex)
                        jobId = s.runAdHocScript(options.file,serverRefs,codeType,options.args,string.atoi(options.timeout),options.email,options.regex)
                    elif options.spolicy and not (options.server or options.servergroup or options.customer or options.facility):
                        serverRefs = []
                        for spolicy,serverlist in s.getServerRefsBySoftwarePolicy(options.spolicy,options.regex).iteritems():
                            serverRefs = serverRefs + serverlist
                        jobId = s.runAdHocScript(options.file,serverRefs,codeType,options.args,string.atoi(options.timeout),options.email,options.regex)
                    elif options.servergroup and not (options.server or options.spolicy or options.customer or options.facility):
                        deviceGroupRefs = s.getDeviceGroupRefs(options.servergroup,options.regex)
                        jobId = s.runAdHocScript(options.file,deviceGroupRefs,codeType,options.args,string.atoi(options.timeout),options.email,options.regex)
                    elif options.customer and not (options.server or options.servergroup or options.spolicy or options.facility):
                        serverRefs = s.getServerRefsByCustomer(options.customer,options.regex)
                        jobId = s.runAdHocScript(options.file,serverRefs,codeType,options.args,string.atoi(options.timeout),options.email,options.regex)
                    elif options.facility and not (options.server or options.servergroup or options.spolicy or options.customer):
                        serverRefs = s.getServerRefsByFacility(options.facility,options.regex)
                        jobId = s.runAdHocScript(options.file,serverRefs,codeType,options.args,string.atoi(options.timeout),options.email,options.regex)
                    else:
                        p.print_help()
                        print "Please provide --id=<Server script> and one of (--server,--servergroup,--spolicy,--customer, or--facility) and --type=<SH,PS1,BAT,VBS> with runadhoc action"
                    if jobId:
                        print "JobID: %s" % jobId
                else:
                    p.print_help()
                    print "Please provide --id=<Server script> and --server=<Server ID or Name>/--servergroup=<Server Group ID or Name> and --type=<SH,PS1,BAT,VBS> with runadhoc action"
            elif re.match('(?i)^create$',arguments[0]):
                if options.file and options.folder and options.type:
                    if re.match('(?i)sh',options.type):
                        codeType = 'SH'
                    elif re.match('(?i)ps1',options.type):
                        codeType = 'PS1'
                    elif re.match('(?i)bat',options.type):
                        codeType = 'BAT'
                    elif re.match('(?i)vbs',options.type):
                        codeType = 'VBS'
                    else:
                        print "--type %s doesn't match sh, ps1, bat, or vbs" % options.type
                        sys.exit(1)
                    print "%s" % s.createServerScript(options.file,
                                                      options.type,
                                                      options.folder,
                                                      options.scriptname,
                                                      options.description,
                                                      options.versionlabel,
                                                      options.superuser,
                                                      options.serverchange)
            else:
                p.print_help()
                print "Please provide an action: %s" % sacliutil.getActionList(action)
        else:
            p.print_help()
            print "Please provide an action: %s" % sacliutil.getActionList(action)
    else:
        p.print_help()
Exemplo n.º 22
0
def main():
    p = sacliutil.standardOptions(
        "server --id=<identifier> [--<modifier options>] [ <action> ]")
    p.add_option('--id', help="")
    p.add_option('--serverscript', help="Use to run a server script.")
    p.add_option('--customfield', help="Use to list or set a customfield.")
    p.add_option(
        '--attribute',
        help="Use to set a server attribute, use info action to see attribute."
    )
    p.add_option('--value', help="Use to set a customfield value.")
    p.add_option(
        '--days',
        help=
        "Use to specify number of days to go back when viewing server history."
    )
    p.add_option(
        '--weeks',
        help=
        "Use to specify number of weeks to go back when viewing server history."
    )
    p.add_option('--dvcid', action="store_true", help="Use to view device id.")
    p.add_option('--customer',
                 help="Specify a servers belonging to a facility.")
    p.add_option(
        '--newcustomer',
        help=
        "Use to assign servers to a new customer name/id. Used with assign action."
    )
    p.add_option('--facility',
                 help="Specify a group of servers belonging to a facility.")
    p.add_option(
        '--spolicy',
        help="Specify a software policy name for servers attached to them.")
    p.add_option('--servername', help="new server name, use with rename.")
    p.add_option('--sgmembers',
                 help="list out servers that belong to a device group.")
    p.add_option('--caname',
                 help="Use with server setca (Set Custom Attribute)")
    p.add_option('--value',
                 help="Use with server setca (Set Custom Attribute)")
    (options, arguments) = p.parse_args()
    s = sacliutil.getSALib(options.username, options.password,
                           options.authfile)

    if options.debug:
        s.setDebug(1)
    if options.id or options.facility or options.customer or options.spolicy or options.sgmembers:
        action = [
            'info', 'policystatus', 'list', 'history', 'updatecustomfield',
            'showcustomfields', 'assign', 'getca', 'setca', 'clean', 'rename',
            'commtest'
        ]
        if options.id and not (options.facility or options.customer
                               or options.spolicy or options.sgmembers):
            serverRefs = s.getServerRefs(options.id, options.regex)
        elif options.facility and not (options.id or options.customer or
                                       options.spolicy or options.sgmembers):
            serverRefs = s.getServerRefsByFacility(options.facility,
                                                   options.regex)
        elif options.customer and not (options.id or options.facility or
                                       options.spolicy or options.sgmembers):
            serverRefs = s.getServerRefsByCustomer(options.customer,
                                                   options.regex)
        elif options.spolicy and not (options.id or options.facility or
                                      options.customer or options.sgmembers):
            serverRefs = []
            for spolicy, serverlist in s.getServerRefsBySoftwarePolicy(
                    options.spolicy, options.regex).iteritems():
                serverRefs = serverRefs + serverlist
        elif options.sgmembers and not (options.id or options.facility or
                                        options.customer or options.spolicy):
            serverRefs = s.getServerGroupInfo(options.sgmembers,
                                              options.regex)['devices']
        else:
            print "Incorrect options given, possibly incorrect combination or the options don't exist."
            p.print_help()
        try:
            if arguments:
                # if arguments[0] == 'info':
                if re.match('[Ii]nfo', arguments[0]):
                    for i in serverRefs:
                        print "ServerRef: %s" % i
                        sacliutil.print_serverinfo(s, 's.getServerInfo', i)
                        print
                elif re.match('[Pp]olicystatus', arguments[0]):
                    policyStates = s.getPolicyAttachableStatesByServerRefs(
                        serverRefs)
                    for sref in serverRefs:
                        print "ServerRef: %s" % sref
                        for policystate in policyStates:
                            if sref.id == policystate.policyAttachable.id:
                                policy = policystate.policyAssociation.policy
                                direct = policystate.policyAssociation.direct
                                remediated = policystate.policyAssociation.remediated
                                attached = policystate.policyAssociation.attached
                                dvcgroup = policystate.policyAssociation.deviceGroups
                                print "policy:%s direct:%s remediated:%s attached:%s dvcgroup:%s" % (
                                    policy, direct, remediated, attached,
                                    dvcgroup)
                        print
                elif re.match('(?i)list$', arguments[0]):
                    for i in serverRefs:
                        print "%s" % i
                elif re.match('(?i)history$', arguments[0]):
                    if options.days:
                        for i in serverRefs:
                            print "Server Name: %s" % i.name
                            for j in s.getServerHistorybyDays(
                                    i, string.atol(options.days)):
                                print "%s" % re.sub('[{}]', '', "%s" % j)
                        #print "%s" % options.days
                        print
                    elif options.weeks:
                        for i in serverRefs:
                            print "Server Name: %s" % i.name
                            for j in s.getServerHistorybyWeeks(
                                    i, string.atol(options.weeks)):
                                print "%s" % re.sub('[{}]', '', "%s" % j)
                        print
                    else:
                        p.print_help()
                        print "With [--days=<num of days> or --weeks=<num of weeks]"
                elif re.match('(?i)updatecustomfields?', arguments[0]):
                    if options.customfield:
                        results = s.setServerCustomFieldsByServerRefs(
                            serverRefs, options.customfield, options.value,
                            options.regex)
                        serverKeys = results.keys()
                        serverKeys.sort()
                        for server in serverKeys:
                            cfKeys = results[server].keys()
                            cfKeys.sort()
                            cfs = results[server]
                            for cf in cfKeys:
                                print "updated %s -> %s: oldvalue=%s newvalue=%s" % (
                                    server, cf, cfs[cf]['oldvalue'],
                                    cfs[cf]['newvalue'])
                    else:
                        print "Must provide --customfield and --value option."
                elif re.match('(?i)updateattribute?', arguments[0]):
                    if options.attribute and options.value:
                        print "updated servers:"
                        for updated_svo in s.setServerAttributeByServerRefs(
                                serverRefs, options.attribute, options.value,
                                options.regex):
                            print "%s" % (updated_svo.ref)
                    else:
                        print "Must provide --attribute and --value option."
                elif re.match('(?i)showcustomfields?', arguments[0]):
                    serverCustomFields = s.getServerCustomFieldsByServerRefs(
                        serverRefs, options.customfield, regex=options.regex)
                    for server in serverCustomFields.keys():
                        print "%s" % server
                        for customfield in serverCustomFields[server]:
                            key = customfield.iterkeys().next()
                            print "%s: %s" % (key, customfield[key])
                        print
                elif re.match('(?i)assign', arguments[0]):
                    if options.newcustomer:
                        customer_ref = s.getCustomerRefs(
                            options.newcustomer, options.regex)
                        if len(customer_ref) < 1:
                            p.print_help()
                            print "No Customer found."
                        elif len(customer_ref) > 1:
                            p.print_help()
                            print "Multiple Customers found, only one can be specified."
                        else:
                            serverGenerator = s.assignCustomerToServerByServerRefs(
                                serverRefs, options.newcustomer, options.regex)
                            for server in serverGenerator:
                                print "%s assigned to customer %s" % server  # server is a tuple returned by serverGenerator...
                    else:
                        print "Must provide --newcustomer with action assign."
                        p.print_help()
                elif re.match('(?i)getca?', arguments[0]):
                    servercas = s.getCustomAttributesOnServerByServerRefs(
                        serverRefs)
                    for serverca in servercas.keys():
                        print "%s" % serverca
                        for ca in servercas[serverca].keys():
                            if not re.match('^__OPSW.*', ca):
                                print "%s : %s" % (ca, servercas[serverca][ca])
                        print
                elif re.match('(?i)setca?', arguments[0]):
                    if options.caname:
                        serverlist = s.setCustomAttributesOnServerByServerRefs(
                            serverRefs, options.caname, options.value)
                        print "Updated Server CA:"
                        for server in serverlist:
                            print "%s" % server
                        print
                    else:
                        p.print_help()
                        print "You need to either provide --caname=<name> and --value=value with action setca."
                elif re.match('(?i)clean$', arguments[0]):
                    print "Cleaning server name (i.e. striping whitespace before and after the name.):"
                    for servervo in s.getServerValueObjectsByServerRefs(
                            serverRefs, options.regex):
                        servervo.name = servervo.name.strip()
                        print "%s" % s.updateServerVO(servervo).ref
                elif re.match('(?i)rename$', arguments[0]):
                    if len(serverRefs) < 1:
                        raise SALib.NoObjectRefFound, options.id
                    elif len(serverRefs) > 1:
                        raise SALib.MultipleObjectRefsFound, options.server
                    servervo = s.getServerValueObjectsByServerRefs(
                        serverRefs, options.regex)[0]
                    servervo.name = options.servername
                    print "Renamed %s to %s" % (
                        serverRefs[0].name,
                        s.updateServerVO(servervo).ref.name)
                elif re.match('(?i)commtest$', arguments[0]):
                    print "%s" % s.serverCommTest(serverRefs)
                else:
                    p.print_help()
                    print "Provide the action: %s" % sacliutil.getActionList(
                        action)
            else:
                p.print_help()
                print "Provide the action: %s" % sacliutil.getActionList(
                    action)
        except SALib.NoServerRefFound, sref:
            print "ERROR: Couldn't find %s." % sref
        except SALib.MultipleServerRefsFound, sref:
            print "ERROR: Multiple Servers found: %s, specify only one server for this operation." % sref
Exemplo n.º 23
0
def main():
    p = sacliutil.standardOptions("cml --id=<customer name> [ <action> ]")
    p.add_option('--id', help="To specify pattern to match cmls.")
    p.add_option('--platform', help="Specify a platform either by id, name, or pattern match.")
    p.add_option('--directory', help="Directory where cml will be written to.")
    (options,arguments) = p.parse_args()
    s = sacliutil.getSALib(options.username,options.password,options.authfile)

    if options.debug:
        s.setDebug(1)
    if options.id:
        action = ['list','stdout','fileout','addplatform','updateplatform']
        if arguments:
            if re.match('[Ll]ist$',arguments[0]):
                for i in s.getCMLRefs(options.id,options.regex):
                    try:
                        if s.isHPSA9x():
                            print "%s|%s" % (sacliutil.printObjectPath(s,[i]),sacliutil.printObjectID(i))
                        else:
                            print "%s|%s" % (i,sacliutil.printObjectID(i))
                    except SALib.AuthorizationDeniedException:
                        print "!!!%s is INACCESSIBLE!!!" % i
                        continue
                    except SALib.NotInFolder,i:
                        print "!!!%s is INACCESSIBLE!!!" % i
                        continue
            elif re.match('[Ss]tdout$',arguments[0]):
                cmlvos = s.getCMLVOs(s.getCMLRefs(options.id,options.regex))
                for cmlvo in cmlvos:
                    print "%s" % cmlvo.text
            elif re.match('[Ff]ileout$',arguments[0]):
                cmlvos = s.getCMLVOs(s.getCMLRefs(options.id,options.regex))
                if options.directory:
                    if os.path.isdir(options.directory):
                        for cmlvo in cmlvos:
                            try:
                                print "Writing to file: %s" % os.path.join(options.directory,cmlvo.name)      
                                output_file = open(os.path.join(options.directory,cmlvo.name), 'w')
                                output_file.write(cmlvo.text)
                                output_file.close()
                            except IOError,args:
                                raise OSError,"%s %s" % (args.strerror, args.filename)
                    else:
                        raise OSError,"No such directory"
                else:
                    for cmlvo in cmlvos:
                        print "Writing to file: %s" % cmlvo.name                    
                        output_file = open(cmlvo.name, 'w')
                        output_file.write(cmlvo.text)
                        output_file.close()
            elif re.match('(?i)addplatform?',arguments[0]):
                if options.platform:
                    print "Adding platform on the following cml(s):"
                    for cmlvo in s.addCMLPlatform(options.id,options.platform,options.regex):
                        print "%s" % cmlvo.ref
                else:
                    p.print_help()
                    print "You need to provide --platform=<platform name>."
            elif re.match('(?i)updateplatform?',arguments[0]):
                if options.platform:
                    print "Updating platform on the following cml(s):"
                    for cmlvo in s.updateCMLPlatform(options.id,options.platform,options.regex):
                        print "%s" % cmlvo.ref
                else:
                    p.print_help()
                    print "You need to provide --platform=<platform name>."
            else:
                p.print_help()
                print "Please provide an action: %s" % sacliutil.getActionList(action)
Exemplo n.º 24
0
def main():
    p = sacliutil.standardOptions(
        "spolicy --id=<identifier> [--<modifier options>] [ <action> ]")
    p.add_option(
        '--id',
        help=
        "Specify a identifier which is an Opsware ID, software policy name, or folder path and software policy name."
    )
    p.add_option('--folderpath',
                 help="Specify a folder path for the software policy refs.")
    p.add_option('--new', help="Specify a new software policy name.")
    p.add_option(
        '--policyitem',
        help=
        "Use with --policyitem when using the action additems or replaceitems."
    )
    p.add_option(
        '--order',
        help=
        "Use with --policyitem and/or action additems or replaceitems to specify the policy item order to add or replace respectively."
    )
    p.add_option('--folder', help="Use with software policy creation.")
    p.add_option('--platform', help="Use with software policy creation.")
    p.add_option('--server',
                 help="Use with software policy install and uninstall.")
    p.add_option('--servergroup',
                 help="Use with software policy install and uninstall.")
    p.add_option('--sgmembers',
                 help="Use with software policy install and uninstall.")
    p.add_option('--name',
                 help="Use with software policy setca (Set Custom Attribute)")
    p.add_option('--value',
                 help="Use with software policy setca (Set Custom Attribute)")
    p.add_option('--recursive',
                 action="store_true",
                 help="Recursively traverse the folders.")
    p.add_option('--spfilter', help="Specify a software policy name filter.")
    (options, arguments) = p.parse_args()
    s = sacliutil.getSALib(options.username, options.password,
                           options.authfile)

    if options.debug:
        s.setDebug(1)
    if options.id:
        action = [
            'list', 'listitems', 'additems', 'replaceitems', 'deleteitems',
            'addplatform', 'updateplatform', 'create', 'install', 'uninstall',
            'getca', 'setca', 'serverlist', 'remediate'
        ]
        if arguments:
            if re.match('[Ll]ist$', arguments[0]):
                objPaths = []
                if options.regex:
                    softwarePolicyRefs = s.getSoftwarePolicyRefs(
                        options.id, True)
                else:
                    softwarePolicyRefs = s.getSoftwarePolicyRefs(options.id)
                for i in softwarePolicyRefs:
                    try:
                        print "%s|%s" % (sacliutil.printObjectPath(
                            s, [i]), sacliutil.printObjectID(i))
                    except SALib.AuthorizationDeniedException:
                        print "!!!%s is INACCESSIBLE!!!" % i
                        continue
                    except SALib.NotInFolder, i:
                        print "!!!%s is INACCESSIBLE!!!" % i
                        continue
            elif re.match('[Ss]erverlist$', arguments[0]):
                for spolicy, serverlist in s.getServerRefsBySoftwarePolicy(
                        options.id, options.regex).iteritems():
                    print "%s" % spolicy
                    for server in serverlist:
                        print "%s" % server
                    print
            elif re.match('[Aa]dditems?', arguments[0]):
                try:
                    if options.policyitem:
                        policyItemRefs = sacliutil.createPolicyItemList(
                            s, options.policyitem)
                        print "%s" % policyItemRefs
                        if options.order:
                            print "%s has been updated." % s.addSoftwarePolicyItem(
                                options.id, policyItemRefs, options.order).ref
                        else:
                            print "%s has been updated." % s.addSoftwarePolicyItem(
                                options.id, policyItemRefs).ref
                    else:
                        print "With --id and action additems you need to provide --policyitem"
                except SALib.DuplicatePolicyItemFound, args:
                    print "The policyitem %s already exist in the software policy." % args
            elif re.match('[Rr]eplaceitems?', arguments[0]):
                if options.policyitem:
                    if options.order:
                        try:
                            policyItemRef = sacliutil.createPolicyItemList(
                                s, options.policyitem)
                            print "%s" % options.policyitem
                            print "%s" % policyItemRef
                            if len(policyItemRef) > 1:
                                print "You need to provide only one --policyitem because you can only replace items one at a time."
                                sys.exit()
                            sref = s.replaceSoftwarePolicyItembyPosition(
                                options.id, policyItemRef[0],
                                options.order).ref
                            print "%s has been updated" % sref
                        except SALib.NoObjectRefFound, args:
                            print "Couldn't find policy item %s to replace" % args
                        except SALib.NotSoftwarePolicyItem, args:
                            print "The referenced item %s can't be added to a software policy." % args
                        except IndexError, args:
                            print "%s is an incorrect SA Object type. Check the issued --policyitem args for the correct type." % \
                                        options.policyitem
Exemplo n.º 25
0
def main():
    p = sacliutil.standardOptions("")
    p.add_option('--id', help="Specify ID or OGFS Script name.")
    p.add_option('--notification',
                 action="store_true",
                 help="Emails notification to the user.")
    p.add_option('--args',
                 help="Arguments to pass to the OGFS Script.",
                 default="")
    p.add_option('--exe',
                 help="Interpreter or shell to use, by default /bin/bash",
                 default="/bin/bash")
    p.add_option('--workingdir', help="Working directory of the OGFS Script.")
    p.add_option('--version', help="Version Label for OGFS Script.")
    (options, arguments) = p.parse_args()
    s = sacliutil.getSALib(options.username, options.password,
                           options.authfile)

    if options.debug:
        s.setDebug(1)
    if options.id:
        action = ['wayrun', 'list', 'run', 'print']
        if arguments:
            if re.match('[Ww]ayrun', arguments[0]):
                if options.args:
                    args = options.args
                else:
                    args = ''
                jobid = s.runOGFSScript(options.id, args, options.notification,
                                        options.workingdir)
                print "%s" % jobid
            elif re.match('[Rr]un', arguments[0]):
                #result = subprocess.Popen(args=s.getOGFSScriptSource(options.id,options.version),shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
                ogfs_ref = s.getOGFSScriptRefs(options.id, options.regex)
                if len(ogfs_ref) > 1:
                    raise SALib.MultipleOGFSScriptFound, ogfs_ref
                script_path = "/tmp/%s-ogfsscript-%s" % (s._SALib__username,
                                                         ogfs_ref[0].id)
                fd = open(script_path, "w+")
                fd.write(s.getOGFSScriptSource(options.id, options.version))
                fd.close()
                os.chmod(script_path, 0700)
                args = []
                if options.exe:
                    args.append(options.exe)
                args = args + [script_path] + shlex.split(options.args)
                ret = subprocess.call(args)
                sys.exit(ret)
                #print "%s" % result.stdout.read()
                #stdErr = result.stderr.read()
                #if stdErr:
                #    print "%s" % stdErr
            elif re.match('[p]rint', arguments[0]):
                print "%s" % s.getOGFSScriptSource(options.id, options.version)
            elif re.match('[Ll]ist', arguments[0]):
                OGFSScriptRefs = s.getOGFSScriptRefs(options.id, options.regex)
                for i in OGFSScriptRefs:
                    try:
                        pathDict = s.getObjectPath([i], False)
                        (parentPath, SP) = os.path.split(pathDict[i])
                        if parentPath == "/":
                            print "%s%s" % (parentPath, i)
                        else:
                            print "%s/%s" % (parentPath, i)
                    except SALib.AuthorizationDeniedException:
                        print "!!!%s is INACCESSIBLE!!!" % i
                        continue
                    except SALib.NotInFolderException:
                        print "!!!%s is INACCESSIBLE!!!" % i
                        continue
            else:
                p.print_help()
                print "Please provide an action: %s" % sacliutil.getActionList(
                    action)
        else:
            p.print_help()
            print "Please provide an action: %s" % sacliutil.getActionList(
                action)
    else:
        p.print_help()
Exemplo n.º 26
0
def main():
    p = sacliutil.standardOptions("spolicy --id=<identifier> [--<modifier options>] [ <action> ]")
    p.add_option('--id', help="Specify a identifier which is an Opsware ID, software policy name, or folder path and software policy name.")
    p.add_option('--folderpath', help="Specify a folder path for the software policy refs.")
    p.add_option('--new', help="Specify a new software policy name.")
    p.add_option('--policyitem', help="Use with --policyitem when using the action additems or replaceitems.")
    p.add_option('--order', help="Use with --policyitem and/or action additems or replaceitems to specify the policy item order to add or replace respectively.")
    p.add_option('--folder', help="Use with software policy creation.")
    p.add_option('--platform', help="Use with software policy creation.")
    p.add_option('--server', help="Use with software policy install and uninstall.")
    p.add_option('--servergroup', help="Use with software policy install and uninstall.")
    p.add_option('--sgmembers', help="Use with software policy install and uninstall.")
    p.add_option('--name', help="Use with software policy setca (Set Custom Attribute)")
    p.add_option('--value', help="Use with software policy setca (Set Custom Attribute)")
    p.add_option('--recursive', action="store_true",help="Recursively traverse the folders.")
    p.add_option('--spfilter', help="Specify a software policy name filter.")
    (options,arguments) = p.parse_args()
    s = sacliutil.getSALib(options.username,options.password,options.authfile)

    if options.debug:
        s.setDebug(1)
    if options.id:
        action = ['list','listitems','additems','replaceitems','deleteitems','addplatform','updateplatform','create','install','uninstall','getca','setca','serverlist','remediate']
        if arguments:
            if re.match('[Ll]ist$',arguments[0]):
                objPaths = []
                if options.regex:
                    softwarePolicyRefs = s.getSoftwarePolicyRefs(options.id,True)
                else:
                    softwarePolicyRefs = s.getSoftwarePolicyRefs(options.id)
                for i in softwarePolicyRefs:
                    try:
                        print "%s|%s" % (sacliutil.printObjectPath(s,[i]),sacliutil.printObjectID(i))
                    except SALib.AuthorizationDeniedException:
                        print "!!!%s is INACCESSIBLE!!!" % i
                        continue
                    except SALib.NotInFolder,i:
                        print "!!!%s is INACCESSIBLE!!!" % i
                        continue
            elif re.match('[Ss]erverlist$',arguments[0]):
                for spolicy,serverlist in s.getServerRefsBySoftwarePolicy(options.id,options.regex).iteritems():
                    print "%s" % spolicy
                    for server in serverlist:
                        print "%s" % server
                    print
            elif re.match('[Aa]dditems?',arguments[0]):
                try:
                    if options.policyitem:
                        policyItemRefs = sacliutil.createPolicyItemList(s,options.policyitem)
                        print "%s" % policyItemRefs
                        if options.order:
                            print "%s has been updated." % s.addSoftwarePolicyItem(options.id,policyItemRefs,options.order).ref
                        else:
                            print "%s has been updated." % s.addSoftwarePolicyItem(options.id,policyItemRefs).ref
                    else:
                        print "With --id and action additems you need to provide --policyitem"
                except SALib.DuplicatePolicyItemFound,args:
                    print "The policyitem %s already exist in the software policy." % args
            elif re.match('[Rr]eplaceitems?',arguments[0]):
                if options.policyitem:
                    if options.order:
                        try:
                            policyItemRef = sacliutil.createPolicyItemList(s,options.policyitem)
                            print "%s" % options.policyitem
                            print "%s" % policyItemRef
                            if len(policyItemRef) > 1:
                                print "You need to provide only one --policyitem because you can only replace items one at a time." 
                                sys.exit()
                            sref = s.replaceSoftwarePolicyItembyPosition(options.id,policyItemRef[0],options.order).ref
                            print "%s has been updated" % sref
                        except SALib.NoObjectRefFound,args:
                            print "Couldn't find policy item %s to replace" % args
                        except SALib.NotSoftwarePolicyItem,args:
                            print "The referenced item %s can't be added to a software policy." % args
                        except IndexError,args:
                            print "%s is an incorrect SA Object type. Check the issued --policyitem args for the correct type." % \
                                        options.policyitem
Exemplo n.º 27
0
def main():
    p = sacliutil.standardOptions("cml --id=<customer name> [ <action> ]")
    p.add_option('--id', help="To specify pattern to match cmls.")
    p.add_option(
        '--platform',
        help="Specify a platform either by id, name, or pattern match.")
    p.add_option('--directory', help="Directory where cml will be written to.")
    (options, arguments) = p.parse_args()
    s = sacliutil.getSALib(options.username, options.password,
                           options.authfile)

    if options.debug:
        s.setDebug(1)
    if options.id:
        action = ['list', 'stdout', 'fileout', 'addplatform', 'updateplatform']
        if arguments:
            if re.match('[Ll]ist$', arguments[0]):
                for i in s.getCMLRefs(options.id, options.regex):
                    try:
                        if s.isHPSA9x():
                            print "%s|%s" % (sacliutil.printObjectPath(
                                s, [i]), sacliutil.printObjectID(i))
                        else:
                            print "%s|%s" % (i, sacliutil.printObjectID(i))
                    except SALib.AuthorizationDeniedException:
                        print "!!!%s is INACCESSIBLE!!!" % i
                        continue
                    except SALib.NotInFolder, i:
                        print "!!!%s is INACCESSIBLE!!!" % i
                        continue
            elif re.match('[Ss]tdout$', arguments[0]):
                cmlvos = s.getCMLVOs(s.getCMLRefs(options.id, options.regex))
                for cmlvo in cmlvos:
                    print "%s" % cmlvo.text
            elif re.match('[Ff]ileout$', arguments[0]):
                cmlvos = s.getCMLVOs(s.getCMLRefs(options.id, options.regex))
                if options.directory:
                    if os.path.isdir(options.directory):
                        for cmlvo in cmlvos:
                            try:
                                print "Writing to file: %s" % os.path.join(
                                    options.directory, cmlvo.name)
                                output_file = open(
                                    os.path.join(options.directory,
                                                 cmlvo.name), 'w')
                                output_file.write(cmlvo.text)
                                output_file.close()
                            except IOError, args:
                                raise OSError, "%s %s" % (args.strerror,
                                                          args.filename)
                    else:
                        raise OSError, "No such directory"
                else:
                    for cmlvo in cmlvos:
                        print "Writing to file: %s" % cmlvo.name
                        output_file = open(cmlvo.name, 'w')
                        output_file.write(cmlvo.text)
                        output_file.close()
            elif re.match('(?i)addplatform?', arguments[0]):
                if options.platform:
                    print "Adding platform on the following cml(s):"
                    for cmlvo in s.addCMLPlatform(options.id, options.platform,
                                                  options.regex):
                        print "%s" % cmlvo.ref
                else:
                    p.print_help()
                    print "You need to provide --platform=<platform name>."
            elif re.match('(?i)updateplatform?', arguments[0]):
                if options.platform:
                    print "Updating platform on the following cml(s):"
                    for cmlvo in s.updateCMLPlatform(options.id,
                                                     options.platform,
                                                     options.regex):
                        print "%s" % cmlvo.ref
                else:
                    p.print_help()
                    print "You need to provide --platform=<platform name>."
            else:
                p.print_help()
                print "Please provide an action: %s" % sacliutil.getActionList(
                    action)
Exemplo n.º 28
0
def main():
    p = sacliutil.standardOptions(
        "folder --id=<identifier> [--<modifier options>] [ <action> ]")
    p.add_option('--id', help="folder path or id")
    p.add_option('--recursive',
                 action="store_true",
                 help="Recursively traverse the folders.")
    p.add_option('--type', help="Filter by SA Object type.")
    (options, arguments) = p.parse_args()
    s = sacliutil.getSALib(options.username, options.password,
                           options.authfile)

    if options.debug:
        s.setDebug(1)
    if options.id:
        action = [
            'info', 'listsaobj', 'list', 'listall', 'remove', 'create',
            'addacl', 'removeacl', 'listacl'
        ]
        try:
            if arguments:
                if re.match('[Ll]ist$', arguments[0]):
                    if options.regex:
                        folderRefs = s.getFolderRefs(options.id, True)
                    else:
                        folderRefs = s.getFolderRefs(options.id, False)
                    for i in folderRefs:
                        try:
                            if i.id == 0:
                                print "/|%s" % sacliutil.printObjectID(i)
                            else:
                                print "%s|%s" % (sacliutil.printObjectPath(
                                    s, [i]), sacliutil.printObjectID(i))
                        except SALib.AuthorizationDeniedException:
                            print "!!!%s is INACCESSIBLE!!!" % i
                            continue
                        except SALib.NotInFolderException:
                            print "!!!%s is INACCESSIBLE!!!" % i
                elif re.match('[Ll]istall', arguments[0]):
                    if options.regex:
                        folderRefs = s.getFolderRefs(options.id, True, True)
                    else:
                        folderRefs = s.getFolderRefs(options.id, False, True)
                    for i in folderRefs:
                        try:
                            print "%s|%s" % (sacliutil.printObjectPath(
                                s, [i]), sacliutil.printObjectID(i))
                            #pathDict = s.getObjectPath([ i ],False)
                            #(parentPath,SP) = os.path.split(pathDict[i])
                            #if parentPath == "/":
                            #    print "%s%s" % (parentPath,i)
                            #else:
                            #    print "%s/%s" % (parentPath,i)
                        except SALib.AuthorizationDeniedException:
                            print "!!!%s is INACCESSIBLE!!!" % i
                            continue
                        except SALib.NotInFolderException:
                            print "!!!%s is INACCESSIBLE!!!" % i
                elif re.match('[Ii]nfo', arguments[0]):
                    print "Folder: %s" % options.id
                    sacliutil.print_folderinfo(s, 's.getFolderInfo',
                                               options.id)
                    print
                elif arguments[0] == 'create':
                    print "Folder: %s" % options.id
                    s.createFolder(options.id)
                elif arguments[0] == "remove":
                    print "Folder: %s" % options.id
                    recursive = False
                    if options.recursive:
                        recursive = True
                    s.removeFolder(options.id, recursive)
                elif re.match('[Ll]istsaobj?', arguments[0]):
                    recursive = False
                    if options.recursive:
                        recursive = True
                    if options.type in folderSAObjType.keys():
                        s.printFolderObj(options.id, recursive, options.type)
                    elif not options.type:
                        s.printFolderObj(options.id, recursive, '')
                    else:
                        print "They type you've referenced in --type does not exist or is not yet implemented."
                        print "The list of valid types are: %s" % folderSAObjType.keys(
                        )
                elif arguments[0] == "addacl":
                    recursive = False
                    applytoparent = False
                    if options.perm and options.usergroup:
                        if options.applytoparent:
                            applytoparent = True
                        if options.recursive:
                            recursive = True
                        addedACL = s.addFolderACLs(options.id, options.perm,
                                                   options.usergroup,
                                                   recursive, applytoparent)
                        for i in addedACL:
                            print "%s" % i
                    else:
                        print "With addacl action you must provide --perm=<permissions> and --usergroup=<usergroup name>"
                        print "perm can be comma delimited string: l,r,w,x"
                        print "where l is list,r is read, w is write, and x is execute"
                        print 'i.e. --perm=l,r,w'
                elif arguments[0] == "listacl":
                    s.listFolderACLs(options.id)
                elif arguments[0] == "removeacl":
                    recursive = False
                    applytoparent = False
                    if options.usergroup:
                        if options.applytoparent:
                            applytoparent = True
                        if options.recursive:
                            recursive = True
                        if options.perm:
                            perm = options.perm
                        else:
                            perm = "l,r,w,x,p"
                            print "Removing all permissions from folder %s for usergroup %s" % (
                                options.id, options.usergroup)
                        removedACL = s.removeFolderACLs(
                            options.id, perm, options.usergroup, recursive)
                        for i in removedACL:
                            print "%s" % i
                    else:
                        p.print_help()
                        print "With removeacl action you must provide --usergroup=<usergroup name>"
                        print "Optionally provide --perm, if not provided then all permissions for usergroup will be removed from the folder"
                        print "perm can be comma delimited string: l,r,w,x"
                        print "where l is list,r is read, w is write, and x is execute"
                        print "i.e. --perm='l,r,w'"
                else:
                    p.print_help()
                    print "Please provide an action: %s" % sacliutil.getActionList(
                        action)
            else:
                p.print_help()
                print "Please provide an action: %s" % sacliutil.getActionList(
                    action)
        except SALib.MultipleFolderRefsFound, args:
            print "ERROR: Multiple folders found: %s." % args
        except SALib.NullSearchValue, args:
            print "ERROR: Empty Search Value given."
Exemplo n.º 29
0
def main():
    p = sacliutil.standardOptions("job --id=<jobid> [--<modifier options>] [ <action> ]")
    p.add_option('--id', help="Use to find SA jobs.")
    (options,arguments) = p.parse_args()
    s = sacliutil.getSALib(options.username,options.password,options.authfile)

    if options.debug:
        s.setDebug(1)
    if options.id:
        action = ['results']
        if arguments:
            if re.match('[Rr]esults?',arguments[0]):
                jobType = s.getJobResults(options.id)['type']
                jobResultDict = s.getJobResults(options.id)['hosts']
                hostKeys = jobResultDict.keys()
                hostKeys.sort()
                for host in hostKeys:
                    if jobType == 'server.script.run':
                        print '-------------------------------------------------------------------------------'
                        print "%s" % host
                        jobResults = jobResultDict[host].keys()
                        jobResults.sort()
                        for i in jobResults:
                            if re.match('(stderr|stdout|tailStderr|tailStdout)',i):
                                print "%s:\n%s" % (i,jobResultDict[host][i])
                            else:
                                print "%s: %s" % (i,jobResultDict[host][i])
                        print '-------------------------------------------------------------------------------'
                        print
                    elif jobType == 'server.os.install':
                        if jobResultDict[host].error:
                            print "FAILED OS Provisioning on %s with JobID %s" % (host,options.id)
                            print "%s" % jobResultDict[host].error.message
                        else:
                            print "COMPLETED OS Provisioning on %s with JobID %s" % (host,options.id)
                            minusInstallProfile = re.sub(r'(-+[A-Za-z0-9. /]*-+\n)(.*\n)*(-+[A-Za-z0-9_. /]*-+\n)',\
                                                         '',\
                                                        jobResultDict[host].elemResultInfo[0].message.defaultMsg,re.MULTILINE)
                            print "%s" % minusInstallProfile
                    elif jobType == 'ogfs.script.run':
                        print "OGFS Host: %s" % host
                        print "JobRef: %s" % jobResultDict[host].jobInfo.ref
                        print "script: %s" % jobResultDict[host].jobInfo.script
                        print "start date: %s" % time.strftime("%a %b %d %H:%M:%S %Z %Y",time.localtime(jobResultDict[host].jobInfo.startDate))
                        print "end date: %s" % time.strftime("%a %b %d %H:%M:%S %Z %Y",time.localtime(jobResultDict[host].jobInfo.endDate))
                        print "parameters: %s" % jobResultDict[host].jobInfo.args.parameters
                        print "timeout: %s" % jobResultDict[host].jobInfo.args.timeOut
                        print "workingDir: %s" % jobResultDict[host].jobInfo.args.workingDir
                        print "stdout: %s" % jobResultDict[host].jobOutput.tailStdout
                    elif jobType == 'program_apx.execute':
                        print "OGFS Host: %s" % host
                        print "JobRef: %s" % jobResultDict[host].jobInfo.ref
                        print "version: %s" % jobResultDict[host].jobInfo.version
                        print "apx: %s" % jobResultDict[host].jobInfo.APX
                        print "start date: %s" % time.strftime("%a %b %d %H:%M:%S %Z %Y",time.localtime(jobResultDict[host].jobInfo.startDate))
                        print "end date: %s" % time.strftime("%a %b %d %H:%M:%S %Z %Y",time.localtime(jobResultDict[host].jobInfo.endDate))
                        print "parameters: %s" % jobResultDict[host].jobInfo.args.parameters
                        print "timeout: %s" % jobResultDict[host].jobInfo.args.timeOut
                        print "workingDir: %s" % jobResultDict[host].jobInfo.args.workingDir
                    elif jobType == 'server.swpolicy.remediate':
                        job_id = string.atol(options.id)
                        j = s.getJobResultsMap(job_id)
                        print "Software Policy JobID %s: %s" % (options.id, s.getJobResults(options.id)['hosts'][options.id])
                        for server_id, job_results in j['host_progress_dic'].iteritems():
                            print "%s: %s" % (s.getServerRefs(server_id)[0], job_results['status'])
            else:
                p.print_help()
                print "Please provide an action: %s" % sacliutil.getActionList(action)
        else:
            p.print_help()
            print "Please provide an action: %s" % sacliutil.getActionList(action)
    else:
        p.print_help()
Exemplo n.º 30
0
def main():
    p = sacliutil.standardOptions(
        "serverscript --id=<identifier> [--<modifier options>] [ <action> ]")
    p.add_option(
        '--id',
        help=
        "Specify server script name, id, or folder path and server script name"
    )
    p.add_option('--server', help="Specify server name or id")
    p.add_option('--servergroup', help="Specify server group by id or path.")
    p.add_option('--spolicy',
                 help="Specify servers by software policy associations.")
    p.add_option('--customer',
                 help="Specify servers by customer associations.")
    p.add_option('--facility',
                 help="Specify servers by facility associations.")
    p.add_option('--file', help="Specify script filename.")
    p.add_option(
        '--folder',
        help="Specify folder by id or path that script will be stored in.")
    p.add_option(
        '--type',
        help=
        "Specify the script extension sh, ps1, bat, or vbs (unix shell, powershell, batch, or visual basic script respectively.)"
    )
    p.add_option(
        '--args',
        default='',
        help="Specify arguments that need to be passed to the script.")
    p.add_option(
        '--timeout',
        default='300',
        help="Specify timeout for the server script. Default is 300 seconds")
    p.add_option(
        '--scriptname',
        default='',
        help=
        "Use this as name instead of the filename for the server script. Default is to use the filename for the server script name."
    )
    p.add_option(
        '--description',
        default='',
        help=
        "Use given description instead of the filename for the server script. Default is to set filename for description."
    )
    p.add_option('--versionlabel',
                 default='',
                 help="Specify version label for the server script.")
    p.add_option(
        '--nosuperuser',
        default=True,
        action="store_false",
        help=
        "Specify whether this script run as a super user or not. Default is set to True."
    )
    p.add_option(
        '--email',
        default=False,
        action="store_true",
        help="Email using SA account information. Default is set to False")
    p.add_option(
        '--noserverchange',
        default=True,
        action="store_false",
        help=
        "Specify whether this script can make changes to the server or not. Default is set to True"
    )
    (options, arguments) = p.parse_args()
    s = sacliutil.getSALib(options.username, options.password,
                           options.authfile)

    if options.debug:
        s.setDebug(1)
    if options.id:
        action = ['info', 'list', 'run']
        if arguments:
            if re.match('[Ii]nfo', arguments[0]):
                for i in s.getServerScriptRefs(options.id, options.regex):
                    print "Server Script: %s" % i.name
                    sacliutil.print_serverscriptinfo(s,
                                                     's.getServerScriptInfo',
                                                     i)
                    folderdict = s.getServerScriptInfo(i)
                    print "location: %s" % s.getObjectPath(
                        [folderdict['folder']])
                    print "source: \n%s" % s.showServerScriptSource(i)
            elif re.match('(?i)list?', arguments[0]):
                serverScriptRefs = s.getServerScriptRefs(
                    options.id, options.regex)
                for i in serverScriptRefs:
                    try:
                        pathDict = s.getObjectPath([i], False)
                        (parentPath, SP) = os.path.split(pathDict[i])
                        if parentPath == "/":
                            print "%s%s" % (parentPath, i)
                        else:
                            print "%s/%s" % (parentPath, i)
                    except SALib.AuthorizationDeniedException:
                        print "!!!%s is INACCESSIBLE!!!" % i
                        continue
                    except SALib.NotInFolderException:
                        print "!!!%s is INACCESSIBLE!!!" % i
                        continue
            elif re.match('(?i)^run$', arguments[0]):
                if options.id and (options.server or options.servergroup
                                   or options.spolicy or options.customer
                                   or options.facility or options.sgmembers):
                    jobId = None
                    if options.server and not (
                            options.servergroup or options.spolicy
                            or options.customer or options.facility):
                        serverRefs = s.getServerRefs(options.server,
                                                     options.regex)
                        jobId = s.runServerScript(options.id, serverRefs,
                                                  options.args, None,
                                                  string.atoi(options.timeout),
                                                  options.email, options.regex)
                    elif options.spolicy and not (
                            options.server or options.servergroup
                            or options.customer or options.facility):
                        serverRefs = []
                        for spolicy, serverlist in s.getServerRefsBySoftwarePolicy(
                                options.spolicy, options.regex).iteritems():
                            serverRefs = serverRefs + serverlist
                        jobId = s.runServerScript(options.id, serverRefs,
                                                  options.args, None,
                                                  string.atoi(options.timeout),
                                                  options.email, options.regex)
                    elif options.servergroup and not (
                            options.server or options.spolicy
                            or options.customer or options.facility):
                        deviceGroupRefs = s.getDeviceGroupRefs(
                            options.servergroup, options.regex)
                        jobId = s.runServerScript(options.id, deviceGroupRefs,
                                                  options.args, None,
                                                  string.atoi(options.timeout),
                                                  options.email, options.regex)
                    elif options.customer and not (
                            options.server or options.servergroup
                            or options.spolicy or options.facility):
                        serverRefs = s.getServerRefsByCustomer(
                            options.customer, options.regex)
                        jobId = s.runServerScript(options.id, serverRefs,
                                                  options.args, None,
                                                  string.atoi(options.timeout),
                                                  options.email, options.regex)
                    elif options.facility and not (
                            options.server or options.servergroup
                            or options.spolicy or options.customer):
                        serverRefs = s.getServerRefsByFacility(
                            options.facility, options.regex)
                        jobId = s.runServerScript(options.id, serverRefs,
                                                  options.args, None,
                                                  string.atoi(options.timeout),
                                                  options.email, options.regex)
                    else:
                        p.print_help()
                        print "Please provide --id=<Server script> and one of (--server,--servergroup,--spolicy,--customer, or--facility) and --type=<SH,PS1,BAT,VBS> with run action"
                    if jobId:
                        print "JobID: %s" % jobId
                else:
                    p.print_help()
                    print "Please provide --id=<SA Server script> and --server=<Server ID or Name>/--servergroup <servergroup id or name> with run action"
            else:
                p.print_help()
                print "Please provide an action: %s" % sacliutil.getActionList(
                    action)
        else:
            p.print_help()
            print "Please provide an action: %s" % sacliutil.getActionList(
                action)
    elif options.file:
        action = ['runadhoc', 'create']
        if arguments:
            if re.match('(?i)^runadhoc$', arguments[0]):
                #                if options.servergroup and options.server:
                #                    p.print_help()
                #                    raise bothSgroupAndServer
                if options.file and (options.server or options.servergroup
                                     or options.spolicy or options.customer
                                     or options.facility) and options.type:
                    jobId = None
                    if re.match('(?i)sh', options.type):
                        codeType = 'SH'
                    elif re.match('(?i)ps1', options.type):
                        codeType = 'PS1'
                    elif re.match('(?i)bat', options.type):
                        codeType = 'BAT'
                    elif re.match('(?i)vbs', options.type):
                        codeType = 'VBS'
                    else:
                        print "--type %s doesn't match sh, ps1, bat, or vbs" % options.type
                        sys.exit(1)
                    if options.server and not (
                            options.servergroup or options.spolicy
                            or options.customer or options.facility):
                        serverRefs = s.getServerRefs(options.server,
                                                     options.regex)
                        jobId = s.runAdHocScript(options.file, serverRefs,
                                                 codeType, options.args,
                                                 string.atoi(options.timeout),
                                                 options.email, options.regex)
                    elif options.spolicy and not (
                            options.server or options.servergroup
                            or options.customer or options.facility):
                        serverRefs = []
                        for spolicy, serverlist in s.getServerRefsBySoftwarePolicy(
                                options.spolicy, options.regex).iteritems():
                            serverRefs = serverRefs + serverlist
                        jobId = s.runAdHocScript(options.file, serverRefs,
                                                 codeType, options.args,
                                                 string.atoi(options.timeout),
                                                 options.email, options.regex)
                    elif options.servergroup and not (
                            options.server or options.spolicy
                            or options.customer or options.facility):
                        deviceGroupRefs = s.getDeviceGroupRefs(
                            options.servergroup, options.regex)
                        jobId = s.runAdHocScript(options.file, deviceGroupRefs,
                                                 codeType, options.args,
                                                 string.atoi(options.timeout),
                                                 options.email, options.regex)
                    elif options.customer and not (
                            options.server or options.servergroup
                            or options.spolicy or options.facility):
                        serverRefs = s.getServerRefsByCustomer(
                            options.customer, options.regex)
                        jobId = s.runAdHocScript(options.file, serverRefs,
                                                 codeType, options.args,
                                                 string.atoi(options.timeout),
                                                 options.email, options.regex)
                    elif options.facility and not (
                            options.server or options.servergroup
                            or options.spolicy or options.customer):
                        serverRefs = s.getServerRefsByFacility(
                            options.facility, options.regex)
                        jobId = s.runAdHocScript(options.file, serverRefs,
                                                 codeType, options.args,
                                                 string.atoi(options.timeout),
                                                 options.email, options.regex)
                    else:
                        p.print_help()
                        print "Please provide --id=<Server script> and one of (--server,--servergroup,--spolicy,--customer, or--facility) and --type=<SH,PS1,BAT,VBS> with runadhoc action"
                    if jobId:
                        print "JobID: %s" % jobId
                else:
                    p.print_help()
                    print "Please provide --id=<Server script> and --server=<Server ID or Name>/--servergroup=<Server Group ID or Name> and --type=<SH,PS1,BAT,VBS> with runadhoc action"
            elif re.match('(?i)^create$', arguments[0]):
                if options.file and options.folder and options.type:
                    if re.match('(?i)sh', options.type):
                        codeType = 'SH'
                    elif re.match('(?i)ps1', options.type):
                        codeType = 'PS1'
                    elif re.match('(?i)bat', options.type):
                        codeType = 'BAT'
                    elif re.match('(?i)vbs', options.type):
                        codeType = 'VBS'
                    else:
                        print "--type %s doesn't match sh, ps1, bat, or vbs" % options.type
                        sys.exit(1)
                    print "%s" % s.createServerScript(
                        options.file, options.type, options.folder,
                        options.scriptname, options.description,
                        options.versionlabel, options.superuser,
                        options.serverchange)
            else:
                p.print_help()
                print "Please provide an action: %s" % sacliutil.getActionList(
                    action)
        else:
            p.print_help()
            print "Please provide an action: %s" % sacliutil.getActionList(
                action)
    else:
        p.print_help()
Exemplo n.º 31
0
def main():
    p = sacliutil.standardOptions("folder --id=<identifier> [--<modifier options>] [ <action> ]")
    p.add_option('--id', help="folder path or id")
    p.add_option('--recursive', action="store_true",help="Recursively traverse the folders.")
    p.add_option('--type', help="Filter by SA Object type.")
    (options,arguments) = p.parse_args()
    s = sacliutil.getSALib(options.username,options.password,options.authfile)

    if options.debug:
        s.setDebug(1)
    if options.id:
        action = ['info','listsaobj','list','listall','remove','create','addacl','removeacl','listacl']
        try:
            if arguments:
                if re.match('[Ll]ist$',arguments[0]):
                    if options.regex:
                        folderRefs = s.getFolderRefs(options.id,True)
                    else:
                        folderRefs = s.getFolderRefs(options.id,False)
                    for i in folderRefs:
                        try:
                            if i.id == 0:
                                print "/|%s" % sacliutil.printObjectID(i)
                            else:
                                print "%s|%s" % (sacliutil.printObjectPath(s,[i]),sacliutil.printObjectID(i))
                        except SALib.AuthorizationDeniedException:
                            print "!!!%s is INACCESSIBLE!!!" % i
                            continue
                        except SALib.NotInFolderException:
                            print "!!!%s is INACCESSIBLE!!!" % i
                elif re.match('[Ll]istall',arguments[0]):
                    if options.regex:
                        folderRefs = s.getFolderRefs(options.id,True,True)
                    else:
                        folderRefs = s.getFolderRefs(options.id,False,True)
                    for i in folderRefs:
                        try:
                            print "%s|%s" % (sacliutil.printObjectPath(s,[i]),sacliutil.printObjectID(i))
                            #pathDict = s.getObjectPath([ i ],False)
                            #(parentPath,SP) = os.path.split(pathDict[i])
                            #if parentPath == "/":
                            #    print "%s%s" % (parentPath,i)
                            #else:
                            #    print "%s/%s" % (parentPath,i)
                        except SALib.AuthorizationDeniedException:
                            print "!!!%s is INACCESSIBLE!!!" % i
                            continue
                        except SALib.NotInFolderException:
                            print "!!!%s is INACCESSIBLE!!!" % i
                elif re.match('[Ii]nfo',arguments[0]):
                    print "Folder: %s" % options.id
                    sacliutil.print_folderinfo(s,'s.getFolderInfo',options.id)
                    print
                elif arguments[0] == 'create':
                    print "Folder: %s" % options.id
                    s.createFolder(options.id)
                elif arguments[0] == "remove":
                    print "Folder: %s" % options.id
                    recursive = False
                    if options.recursive:
                        recursive = True
                    s.removeFolder(options.id,recursive)
                elif re.match('[Ll]istsaobj?',arguments[0]):
                    recursive = False
                    if options.recursive:
                        recursive = True
                    if options.type in folderSAObjType.keys():
                        s.printFolderObj(options.id,recursive,options.type)
                    elif not options.type:
                        s.printFolderObj(options.id,recursive,'')
                    else:
                        print "They type you've referenced in --type does not exist or is not yet implemented."
                        print "The list of valid types are: %s" % folderSAObjType.keys()
                elif arguments[0] == "addacl":
                    recursive = False
                    applytoparent = False
                    if options.perm and options.usergroup:
                        if options.applytoparent:
                            applytoparent = True
                        if options.recursive:
                            recursive = True
                        addedACL = s.addFolderACLs(options.id,options.perm,options.usergroup,recursive,applytoparent)
                        for i in addedACL:
                            print "%s" % i
                    else:
                        print "With addacl action you must provide --perm=<permissions> and --usergroup=<usergroup name>"
                        print "perm can be comma delimited string: l,r,w,x"
                        print "where l is list,r is read, w is write, and x is execute"
                        print 'i.e. --perm=l,r,w'
                elif arguments[0] == "listacl":
                    s.listFolderACLs(options.id)
                elif arguments[0] == "removeacl":
                    recursive = False
                    applytoparent = False
                    if options.usergroup:
                        if options.applytoparent:
                            applytoparent = True
                        if options.recursive:
                            recursive = True
                        if options.perm:
                            perm = options.perm
                        else:
                            perm = "l,r,w,x,p"
                            print "Removing all permissions from folder %s for usergroup %s" % (options.id,options.usergroup)
                        removedACL = s.removeFolderACLs(options.id,perm,options.usergroup,recursive)
                        for i in removedACL:
                            print "%s" % i
                    else:
                        p.print_help()
                        print "With removeacl action you must provide --usergroup=<usergroup name>"
                        print "Optionally provide --perm, if not provided then all permissions for usergroup will be removed from the folder"
                        print "perm can be comma delimited string: l,r,w,x"
                        print "where l is list,r is read, w is write, and x is execute"
                        print "i.e. --perm='l,r,w'"
                else:
                    p.print_help()
                    print "Please provide an action: %s" % sacliutil.getActionList(action)
            else:
                p.print_help()
                print "Please provide an action: %s" % sacliutil.getActionList(action)
        except SALib.MultipleFolderRefsFound,args:
            print "ERROR: Multiple folders found: %s." % args
        except SALib.NullSearchValue,args:
            print "ERROR: Empty Search Value given."