コード例 #1
0
def getAllZip(user,passw):
	ts=twistserver.TwistServer()
        ts.authenticate(user, passw)
        zipService=ts.pkg.ZIPService
	filter=Filter()
	lzipRef=zipService.findZIPRefs(filter)
	return lzipRef
コード例 #2
0
def get_policies(platform, sw_policy_filter=None, patch_policy_filter=None):
    policies = {}
    policies['sw'] = None
    policies['patch'] = None
    swps = ts.swmgmt.SoftwarePolicyService
    wpps = ts.swmgmt.WindowsPatchPolicyService
    if sw_policy_filter:
        swpf = Filter()
        swpf.expression = "(software_policy_platform_id EQUAL_TO %s) & (%s)" % (platform.id, sw_policy_filter)
        swpf.objectType = 'software_policy'
        sw_policies = swps.findSoftwarePolicyRefs(swpf)
        #print sw_policies
        if len(sw_policies) > 0:
            policies['sw'] = sw_policies
    if patch_policy_filter:
        wppf = Filter()
        wppf.expression = "(patch_policy_platform_id EQUAL_TO %s) & (%s)" % (platform.id, patch_policy_filter)
        wppf.objectType = 'patch_policy'
        patch_policies = wpps.findWindowsPatchPolicyRefs(wppf)
        if len(patch_policies) > 0:
            policies['patch'] = patch_policies
    return policies
コード例 #3
0
def map_by_platform_facility(facility_filter, platform_filter, server_filter, chunk=50):
    result_map_array = []
    fac_filter = Filter()
    fac_filter.expression = facility_filter
    fac_filter.objectType = 'facility'
    plat_filter = Filter()
    plat_filter.expression = platform_filter
    plat_filter.objectType = 'platform'
    srv_filter = Filter()
    srv_filter.expression = server_filter
    srv_filter.objectType = 'server'
    target_facilities = ts.locality.FacilityService.findFacilityRefs(fac_filter)
    target_platforms = ts.device.PlatformService.findPlatformRefs(plat_filter)
    #print target_facilities
    #print target_platforms
    for facility in target_facilities:
        for platform in target_platforms:
            combined_filter = Filter()
            combined_filter.expression = "(%s)&(device_facility_id EQUAL_TO %s)&(device_platform_id EQUAL_TO %s)" % (
            server_filter, facility.id, platform.id)
            servers = ts.server.ServerService.findServerRefs(combined_filter)
            i = 0
            print 'MAP Result: %s results for: %s' % (len(servers), combined_filter.expression)
            if len(servers) > 0:
                for batch_iter in batch(servers, chunk):
                    result_dict = {}
                    result_dict['facility'] = facility
                    result_dict['platform'] = platform
                    result_dict['chunk'] = i
                    server_array = []
                    for srv in batch_iter:
                        server_array.append(srv)
                    result_dict['target_servers'] = server_array
                    result_map_array.append(result_dict)
                    i = i + 1

    return result_map_array
コード例 #4
0
def getAllSPDate(user, passw):
    file = open("lastModifSP.csv", "w")
    ts = twistserver.TwistServer()
    ts.authenticate(user, passw)
    spService = ts.swmgmt.SoftwarePolicyService
    lspRef = spService.findSoftwarePolicyRefs(Filter())
    lspVO = spService.getSoftwarePolicyVOs(lspRef)
    for sp in lspVO:
        date = datetime.datetime.fromtimestamp(float(
            sp.modifiedDate)).strftime('%Y-%m-%d %H:%M')
        file.write(
            str(sp.name) + ";" + str(date) + ";" + str(sp.modifiedBy) + ";" +
            getIdFromRef(sp.getRef()) + "\n")
    file.close()
    return "ok"
コード例 #5
0
def getAllZipDate(user, passw):
    file = open("lastModifZIP.csv", "w")
    ts = twistserver.TwistServer()
    ts.authenticate(user, passw)
    zipService = ts.pkg.ZIPService
    filter = Filter()
    lzipRef = zipService.findZIPRefs(filter)
    lzipVO = zipService.getZIPVOs(lzipRef)
    for zip in lzipVO:
        date = datetime.datetime.fromtimestamp(float(
            zip.modifiedDate)).strftime('%Y-%m-%d %H:%M')
        size = round(zip.fileSize / 1048576.0, 2)
        file.write(
            str(zip.name) + ";" + str(date) + ";" + str(zip.modifiedBy) + ";" +
            str(size) + ";" + getIdFromRef(zip.getRef()) + "\n")
    file.close()
    return "ok"
コード例 #6
0
def CreateWindowsPatchPolicy(policyName, platformRef, description=None):
    try:
        # check for existing policy by name
        filter = Filter()
        filter.expression = '(patch_policy_name = "%s")' % (policyName)
        policyRefs = wpps.findWindowsPatchPolicyRefs(filter)

        if len(policyRefs) == 1:
            if description:
                # found policy... change description and return it.
                policyVO = wpps.getWindowsPatchPolicyVO(policyRefs[0])
                if policyVO.description != description:
                    logger.debug(
                        "Updating existing Policy %s for platform %s" %
                        (policyName, platformRef.name))
                    policyVO.description = description
                    wpps.update(policyRefs[0], policyVO, 0, 1)
                else:
                    logger.debug("Found existing Policy %s for platform %s" %
                                 (policyName, platformRef.name))
                    return policyRefs[0]
            else:
                logger.debug("Found existing Policy %s for platform %s" %
                             (policyName, platformRef.name))
                return policyRefs[0]
        elif len(policyRefs) == 0:
            # no policies found... create it.
            logger.debug("Creating Policy %s for platform %s" %
                         (policyName, platformRef.name))
            wppVO = WindowsPatchPolicyVO()
            wppVO.name = policyName
            wppVO.platform = platformRef
            wppVO.type = 'STATIC'
            wppVO.description = description
            wppVO = wpps.create(wppVO)
        else:
            logger.error("Policy not unique by filter %s" % filter.expression)
            return
        policyRefs = wpps.findWindowsPatchPolicyRefs(filter)
        return policyRefs[0]
    except Exception, detail:
        logger.error(
            "Exception occurred during Windows patch Policy creation: %s" %
            (detail))
        return
コード例 #7
0
    print "Script Start .......... " + time.strftime(
        "%Y-%m-%d %H:%M:%S", time.gmtime(info.startDate))
    print "Script End ............ " + time.strftime("%Y-%m-%d %H:%M:%S",
                                                     time.gmtime(info.endDate))
    print "Reason for Blocked .... %s" % (info.blockedReason)
    print "Reason for Canceled ... %s" % (info.canceledReason)
    print "Schedule .............. %s" % (info.schedule)
    print "Notification .......... %s" % (info.notification)
    print "Duration .............. %d seconds " % (int(info.endDate -
                                                       info.startDate))


####################################################################### }}} 1
## Query to find Policy/ies ########################################### {{{ 1

pol_filter = Filter()
if POLICY_NAME:
    pol_filter.expression = 'SoftwarePolicyVO.name like "%s"' % (POLICY_NAME)
elif POLICY_OID:
    pol_filter.expression = 'software_policy_folder_id = %s' % (POLICY_OID)
else:
    sys.stderr.write("#- None policy refference (Name/Oid) given !\n")
    sys.exit(1)

policies = policyservice.findSoftwarePolicyRefs(pol_filter)

if len(policies) < 1:
    sys.stderr.write("#- None Software Policy found !\n")
    sys.exit(1)

for policy in policies:
コード例 #8
0
    except getopt.GetoptError:
        parser.print_help()
        sys.exit(2)
    if opts.username and opts.password:
        ts.authenticate(opts.username, opts.password)
    elif os.environ.has_key('SA_USER') and os.environ.has_key('SA_PWD'):
        ts.authenticate(os.environ['SA_USER'], os.environ['SA_PWD'])
    else:
        print "Username and Password not provided. Script may fail unless running in OGSH. \nSpecify with -u username -p password"

    try:
        job_service = ts.job.JobService
    except:
        print "Error initializing services to HPSA"
        sys.exit(2)

    job_filter = Filter()
    print opts.filter
    job_filter.expression = "(%s)" % opts.filter
    print job_filter.expression
    job_refs = job_service.findJobRefs(job_filter)
    print job_refs

    for ref in job_refs:
        vo = job_service.getJobInfoVO(ref)
        start_time = time.strftime(
            '%Y-%m-%d %H:%M:%S',
            time.localtime(vo.jobArgs.actionPhaseArguments.scheduleDate))
        print "%s,%s,%s" % (vo.userTag, start_time,
                            vo.jobArgs.globalArguments.rebootOption)
コード例 #9
0
  #print("#: USER='******' PASS='******'" % (USER,PASS))
except:
  sys.stderr.write("#- ENV[CRED_HPSA] not found #2 !\n")
  sys.exit(1)

# Twist session
ts=twistserver.TwistServer()
ts.authenticate(USER,PASS)

####################################################################### }}} 1
## List Customers ##################################################### {{{ 1

customers=[]
if MODE_LIST or MODE_GETOID or MODE_SET:
  customerservice = ts.locality.CustomerService
  cus_filter = Filter()
  customers = []
  
  if CUSTOM_NAME:
    cus_filter.expression = '((CustomerVO.name like "%s") | '       \
                            '(CustomerVO.displayName like "%s") | ' \
                            '(customer_rc_name like "%s"))' %       \
                            (CUSTOM_NAME, CUSTOM_NAME, CUSTOM_NAME)
    customers = customerservice.findCustomerRefs(cus_filter)
  elif CUSTOM_OID:
    cus_filter.expression =  'customer_rc_id = "%s"' % (CUSTOM_OID) # worked in 10.20
    #cus_filter.expression =  'customer_dvc_id == "%s"' % (CUSTOM_OID) # worked in 10.20
    customers = customerservice.findCustomerRefs(cus_filter)
    #customers = [ customerservice.getCustomerVO(CUSTOM_OID) ]
    #customers = [ customerservice.CustomerRef(CUSTOM_OID) ]
    #print "#: DEBUG3"
コード例 #10
0
sys.path.append("/opt/opsware/pylibs27")
from pytwist import *
from pytwist.com.opsware.search import Filter

# Connect twist
ts = twistserver.TwistServer()
if len(sys.argv) == 1:
    print "Input is null, Please input a hostname"
    sys.exit(1)
else:
    hostName = sys.argv[1]

# Get Server Object Info
serverservice = ts.server.ServerService
filter = Filter()
#ServerVO.hostName是主机名, ServerVO.name是SA name
filter.expression = 'ServerVO.name = "%s"' % (hostName)
server = serverservice.findServerRefs(filter)
if len(server) == 0:
    print "Input error, Host not found"
    sys.exit(1)
else:
    print "Find Server: ", server

# Run Communication Test
jobinfo = serverservice.runAgentCommTest(server)

# Get Job Info
jobservice = ts.job.JobService
jobservice.getJobInfoVO(jobinfo)
コード例 #11
0
        ts.authenticate(opts.username, opts.password)
    elif os.environ.has_key('SA_USER') and os.environ.has_key('SA_PWD'):
        ts.authenticate(os.environ['SA_USER'], os.environ['SA_PWD'])
    else:
        print "Username and Password not provided. Script may fail unless running in OGSH. \n Specify with -u username -p password"

    try:
        device_names = opts.devices.split(',')
    except:
        print "Error Parsing devices. Ensure they are in comma separated format"

    count = 0
    out_dict = []
    for nas_device in device_names:

        deviceFilter = Filter()
        deviceFilter.expression = "hostName = %s" % nas_device

        device = ts.nas.NetworkDeviceService.findNetworkDeviceRefs(
            deviceFilter)
        ntVOFilter = Filter()
        ntVOFilter.expression = "deviceId = %s" % device[0].id
        print nas_device
        ntVOs = ts.nas.NetworkTopologyService.findNetworkTopologyVOs(
            ntVOFilter)
        for ntVO in ntVOs:
            count += 1
            ntVORow = {}

            if ntVO.remoteSasServerId is not None:
                macId = iter(ntVO.macAddress)
コード例 #12
0
try:
    server_service = ts.server.ServerService
    user_role_service = ts.fido.UserRoleService
    folder_service = ts.folder.FolderService
except:
    print "Error initializing services to HPSA"
    sys.exit(2)
###END INTIALIZATION

# Script specific functions

# Main Script
if (__name__ == '__main__'):
    target_folder = FolderRef(long(opts.folder))
    role_filter = Filter()
    role_filter.expression = 'UserRoleVO.roleName CONTAINS PATCH'
    role_filter.objectType = 'user_role'
    roles = user_role_service.findUserRoleRefs(role_filter)

    access_levels = ['READ', 'X']
    if len(roles) > 0:
        role_acls = []
        for role in roles:
            for access_level in access_levels:
                print "ACL: %s rights to %s. Folder: %s" % (
                    access_level, role.name, target_folder.name)
                access_acl = FolderACL()
                access_acl.folder = target_folder
                access_acl.role = role
                access_acl.accessLevel = access_level
コード例 #13
0
        logger.info(
            "Username and Password not provided. Script may fail unless running in OGSH. \n Specify with -u username -p password"
        )

    try:
        server_service = ts.server.ServerService
        platform_service = ts.device.PlatformService
        wpps = ts.swmgmt.WindowsPatchPolicyService
        hotfix_service = ts.pkg.windows.HotfixService
        update_rollup_service = ts.pkg.windows.UpdateRollupService
        service_pack_service = ts.pkg.windows.ServicePackService
    except:
        logger.error("Error initializing services to HPSA")
        sys.exit(2)

    filter = Filter()
    filter.expression = '((platform_name CONTAINS "2008")|(platform_name CONTAINS "2012")|(platform_name CONTAINS "2016")) (platform_name CONTAINS "Windows") & (platform_name NOT_CONTAINS "IA64") & (platform_name NOT_CONTAINS "Windows 2000") & (platform_name NOT_CONTAINS "Windows XP") & (platform_name NOT_CONTAINS "Windows NT 4.0")'
    if opts.platform_filter:
        filter.expression = "%s & (%s)" % (filter.expression,
                                           opts.platform_filter)
    platformRefs = platform_service.findPlatformRefs(filter)

    nameTemplate = Template(opts.policy_name)
    policyDict = {}

    patchBlackList = ["890830"]
    if opts.blacklist:
        mergedList = patchBlackList + re.sub(r'\s', '',
                                             opts.blacklist).split(',')
        patchBlackList = mergedList
コード例 #14
0
def getAllSP(user,passw):
	ts=twistserver.TwistServer()
        ts.authenticate(user, passw)
	spService=ts.swmgmt.SoftwarePolicyService
	lspRef=spService.findSoftwarePolicyRefs(Filter())
	return lspRef
コード例 #15
0
        sys.stderr.write("#- ENV[CRED_HPSA] not found #1 !\n")
        sys.exit(1)
    #(USER,PASS)=os.environ['CRED_HPSA'].split('%',1)
    #print("#: USER='******' PASS='******'" % (USER,PASS))
except:
    sys.stderr.write("#- ENV[CRED_HPSA] not found #2 !\n")
    sys.exit(1)

# Twist session
ts = twistserver.TwistServer()
ts.authenticate(USER, PASS)

####################################################################### }}} 1
## Query to find Script/s ############################################# {{{ 1

scr_filter = Filter()
if SCRIPT_NAME:
    scr_filter.expression = 'ServerScriptVO.name like "%s"' % (SCRIPT_NAME)
elif SCRIPT_OID:
    scr_filter.expression = 'server_script_oid = %s' % (SCRIPT_OID)
else:
    sys.stderr.write("#- None script refference (Name/Oid) given !\n")
    sys.exit(1)

scriptservice = ts.script.ServerScriptService
scripts = scriptservice.findServerScriptRefs(scr_filter)

if len(scripts) < 1:
    sys.stderr.write("#- None Script found !\n")
    sys.exit(1)
コード例 #16
0
        print "Username and Password not provided. Script may fail unless running in OGSH. \n Specify with -u username -p password"

    try:
        server_service = ts.server.ServerService
        server_script_service = ts.script.ServerScriptService
        device_group_service = ts.device.DeviceGroupService
        auth_service = ts.fido.AuthorizationService
    except:
        print "Error initializing services to HPSA"
        sys.exit(2)

    input_file = csv.DictReader(open(opts.file_name))

    server_tuple = []
    for row in input_file:
        server_filter = Filter()
        server_filter.expression = "ServerVO.hostName BEGINS_WITH %s" % row[
            "hostname"].split(".")[0]
        server_refs = server_service.findServerRefs(server_filter)

        if (len(server_refs) == 1):
            print "Success: %s" % server_refs[0].name
            one_ref = [server_refs[0]]
            server_tuple.append(server_refs[0])
        else:
            print "Could not find 1 entries for: %s" % row["hostname"]

    filtered_refs = auth_service.filterSingleTypeResourceList(
        OperationConstants.EXECUTE_SERVER_SCRIPT, server_tuple)
    script_ref = ServerScriptRef(long(opts.script))
    current_time = long(time.time())
コード例 #17
0
ファイル: check_server.py プロジェクト: netskyi/ops-toolbox
    print "Set customer is: %s" % customer
    if customer not in cust_list or ops not in ops_list:
        print "Customer not in {Windows|LINUX|RS6000|SECURITY|BSAE}, Please re-enter it"
        sys.exit(1)
else:
    print "Input incorrect, Please check"
    print "Example set_customer.py {SA name} {set|check} {Windows|LINUX|RS6000|SECURITY|BSAE}"
    sys.exit(1)

# Connect Twist API
ts = twistserver.TwistServer()

# Get Server Object Info
serverservice = ts.server.ServerService
customerservice = ts.locality.CustomerService
filter = Filter()
filter.expression = 'ServerVO.hostName = "%s"' % (hostName)
filter1 = Filter()
filter1.expression = 'CustomerVO.name = "%s"' % (customer)
server = serverservice.findServerRefs(filter)
ops_server = serverservice.getServerVO(server[0])
set_server = server[0]
customers = customerservice.findCustomerRefs(filter1)
set_customer = customers[0]
if len(server) == 0:
    print "Server name input is: ", hostName
    print "Server not found, Please check"
    sys.exit(1)

if ops == "check":
    print ""