def main(argv): # Gets the details the user is looking for try: opts, args = getopt.getopt(argv, "hd:s:", ["deviceGroupId=", "serverId="]) except getopt.GetoptError: usage() sys.exit(1) if len(sys.argv) < 4 : usage() sys.exit(1) for opt, arg in opts: if opt == '-h': print 'addserverToDeviceGroup.py -d <deviceGroupId> -s <serverId>' sys.exit() elif opt in ("-d", "--deviceGroupId"): deviceGroupID = arg elif opt in ("-s", "--serverId"): serverID = arg filter = Filter() filter.expression = 'DeviceGroupVO.pK EQUAL_TO "%s"' % deviceGroupID filter2 = Filter() filter2.expression = 'ServerVO.pK EQUAL_TO "%s"' % serverID deviceGroup_refs = ds.findDeviceGroupRefs(filter) serverRefs = ss.findServerRefs(filter2) for serverRef in serverRefs: ss.addDeviceGroups(serverRef,deviceGroup_refs)
def getJobsStats(): jobService=ts.job.JobService filtre=Filter() filtre.objectType='job' filtre.expression="JobInfoVO.startDate within_last_months 1" result=jobService.findJobRefs(filtre) number=len(result) return str(number)
def getAllZip(user,passw): ts=twistserver.TwistServer() ts.authenticate(user, passw) zipService=ts.pkg.ZIPService filter=Filter() lzipRef=zipService.findZIPRefs(filter) return lzipRef
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
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
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"
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"
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
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)
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: 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) sh_info=[] server_filter = Filter() server_filter.expression="(%s)" % (opts.filter) server_refs=server_service.findServerRefs(server_filter) shvos=server_service.getServerHardwareVOs(server_refs) for sh in shvos: server={} server['name']=sh.ref.name server['id']=sh.ref.id server['interfaces']=[] for intf in sh.interfaces: interface={} interface['ipAddress']=intf.ipAddress interface['hardwareAddress']=intf.hardwareAddress interface['netmask']=intf.netmask interface['slot']=intf.slot
#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"
else: print( "Username and Password not provided. Script may fail unless running in OGSH. \nSpecify 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) sh_info = [] server_filter = Filter() server_filter.expression = "(%s)" % (opts.filter) server_refs = server_service.findServerRefs(server_filter) server_vos = server_service.getServerVOs(server_refs) for server_vo in server_vos: server = {} server['name'] = server_vo.ref.name server['id'] = server_vo.ref.id server['tools_version'] = "0" server['tools_date'] = "0" server['tools_count'] = 0 pkgs = server_service.getInstalledSoftware(server_vo.ref) for p in pkgs: vmware_re = re.compile(r"vmware tools", flags=re.IGNORECASE) if p.name: match = re.search(vmware_re, p.name)
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) macProper = ":".join(a+b for a,b in zip(macId,macId)) serverFilter = Filter()
else: print "Username and Password not provided. Script may fail unless running in OGSH. \nSpecify 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 virtual_service = ts.v12n.V12nVirtualServerService hv_service = ts.v12n.V12nHypervisorService except: print "Error initializing services to HPSA" sys.exit(2) sh_info=[] server_filter = Filter() server_filter.expression="(%s)" % (opts.filter) server_filter.objectType='v12n_virtual_machine' server_refs=virtual_service.findV12nVirtualServerRefs(server_filter) shvos=virtual_service.getV12nVirtualServerVOs(server_refs) for sh in shvos: print sh.detail.name server={} server['name']=sh.detail.name server['hypervisor']=sh.hypervisor.name hv_vo = hv_service.getV12nHypervisorVO(sh.hypervisor) hv_hw_vo = server_service.getServerHardwareVO(hv_vo.server) server['hypervisor_cpu_count'] = len(hv_hw_vo.cpus) server['hypervisor_cpu_model'] = hv_hw_vo.cpus[0].model sh_info.append(server)
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)
import subprocess import time sys.path.append("/opt/opsware/agent/pylibs") #sys.path.append("/opt/opsware/pylibs") from pytwist import * from pytwist.com.opsware.search import Filter # Check for the command-line argument. if len(sys.argv) < 2: print 'You must specify part of the hostname as the search target.' print "Example: " + sys.argv[0] + " " + "opsware.com" sys.exit(2) # Construct a search filter. filter = Filter() filter.expression = 'ServerVO.hostname EQUAL_TO "%s"' % (sys.argv[1]) # Create a TwistServer object. ts = twistserver.TwistServer() # Authenticate by passing an SA user name and password. try: ts.authenticate("jgoodman","svvs1234") except: print "Authentication failed." sys.exit(2) # Get a reference to ServerService. serverservice = ts.server.ServerService PhysicalDiskservice = ts.storage.PhysicalDiskService interfacecomponent = ts.server.InterfaceComponent
import sys sys.path.append("/opt/opsware/agent/pylibs") from pytwist import * from pytwist.com.opsware.search import Filter # Create a TwistServer object. ts = twistserver.TwistServer() # Authenticate by passing an SA username and password try: ts.authenticate('admin', 'opsware_admin') except: print "Authentication failed." sys.exit(2) # Construct a search filter. filter = Filter() filter.expression = 'ServerVO.name *=* "%s"' % 'rhel55' filter.objectType = 'device' # Get a reference to ServerService. serverservice = ts.server.ServerService # Perform the search, returning server references. serverRef = serverservice.findServerRefs(filter) print "-------server %s" % serverRef # Contruct a search filter. filter = Filter() filter.expression = 'AuditTaskVO.name *=* "%s"' % 'policy1' filter.objectType = 'audit_task' # Get a reference to AuditTaskService.
import sys sys.path.append("/opt/opsware/agent/pylibs") from pytwist import * from pytwist.com.opsware.search import Filter # Create a TwistServer object. ts = twistserver.TwistServer() # Authenticate by passing an SA username and password try: ts.authenticate('admin', 'opsware_admin') except: print "Authentication failed." sys.exit(2) # Construct a search filter. filter = Filter() filter.expression = 'ServerVO.name *=* "%s"' % (sys.argv[1]) filter.objectType = 'device' # Get a reference to ServerService. serverservice = ts.server.ServerService # Perform the search, returning a tuple of references. servers = serverservice.findServerRefs(filter) # Print some attrs for server in servers: vo = serverservice.getServerVO(server) print "Name: " + vo.name print " Management IP: " + vo.managementIP print " OS Version: " + vo.osVersion
def getAllSP(user,passw): ts=twistserver.TwistServer() ts.authenticate(user, passw) spService=ts.swmgmt.SoftwarePolicyService lspRef=spService.findSoftwarePolicyRefs(Filter()) return lspRef
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
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
try: server_service=ts.server.ServerService server_script_service=ts.script.ServerScriptService device_group_service=ts.device.DeviceGroupService except: print "Error initializing services to HPSA" sys.exit(2) input_file=csv.DictReader(open(opts.file_name)) dg=DeviceGroupRef(opts.group) server_tuple=[] i=0 for row in input_file: i=i+1 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): one_ref=[server_refs[0]] server_tuple.append(server_refs[0]) try: #print "Adding to group" device_group_service.addDevices(dg,one_ref) print "Success: %s" % server_refs[0].name except: print "Failed to add:%s" % server_refs[0].name else: print "Found %s entries for:%s" % (len(server_refs),row["hostname"])
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: server_service = ts.server.ServerService server_script_service = ts.script.ServerScriptService device_group_service = ts.device.DeviceGroupService auth_service = ts.fido.AuthorizationService swps = ts.swmgmt.SoftwarePolicyService wpps = ts.swmgmt.WindowsPatchPolicyService except: print "Error initializing services to HPSA" sys.exit(2) filter = Filter() filter.expression = opts.filter print filter policies = wpps.findWindowsPatchPolicyRefs(filter) for policy in policies: print long(policy.id) wppvo = wpps.getWindowsPatchPolicyVO(policy) print "Clearing %s" % wppvo.name if (len(wppvo.associatedServers) != 0): servers = wppvo.associatedServers wpps.detachFromPolicies([policy], servers) if (len(wppvo.associatedDeviceGroups) != 0): device_groups = wppvo.associatedDeviceGroups wpps.detachFromPolicies([policy], device_groups) if (int(opts.delete) == 1): print "Deleting %s" % wppvo.name
#(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) serverservice = ts.server.ServerService jobservice = ts.job.JobService # Query to HPSA servers = [] if MODE_REF: filter = Filter() if SEARCH_NAME: filter.expression = 'ServerVO.name like "%s"' % (SEARCH_NAME) if SEARCH_HOST: filter.expression = 'ServerVO.hostName like "%s"' % (SEARCH_HOSTNAME) if SEARCH_ADDR: filter.expression='((device_interface_ip = "%s") | ' \ '(device_management_ip = "%s"))' % (SEARCH_ADDR,SEARCH_ADDR) if SEARCH_ALL: filter.expression='((ServerVO.name like "%s") | ' \ '(ServerVO.hostName like "%s") | ' \ '(device_interface_ip = "%s") | ' \ '(device_management_ip = "%s"))' \ % (SEARCH_ALL,SEARCH_ALL,SEARCH_ALL,SEARCH_ALL) servers = serverservice.findServerRefs(filter)
import subprocess import time sys.path.append("/opt/opsware/agent/pylibs") #sys.path.append("/opt/opsware/pylibs") from pytwist import * from pytwist.com.opsware.search import Filter # Check for the command-line argument. if len(sys.argv) < 2: print 'You must specify part of the hostname as the search target.' print "Example: " + sys.argv[0] + " " + "opsware.com" sys.exit(2) #print 'Host:', sys.argv[1] # Construct a search filter. filter = Filter() filter.expression = 'device_hostname *=* "%s"' % (sys.argv[1]) # Create the TwistServerobject. ts = twistserver.TwistServer() # Authenticate by passing an SA user name and password. try: ts.authenticate("jgoodman","svvs1234") except: print "Authentication failed." sys.exit(2) # Get a reference to ServerService. serverservice = ts.server.ServerService PhysicalDiskservice = ts.storage.PhysicalDiskService interfacecomponent = ts.server.InterfaceComponent
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
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: 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) platform_filter = "device_platform_name CONTAINS Win" server_filter = Filter() print opts.filter server_filter.expression = "(%s)&(%s)" % (opts.filter, platform_filter) print server_filter.expression server_refs = server_service.findServerRefs(server_filter) for batch_iter in batch(server_refs, int(opts.batch_size)): server_array = [] for srv in batch_iter: server_array.append(srv) filtered_refs = auth_service.filterSingleTypeResourceList( OperationConstants.WRITE_DEVICE, server_array) if int(opts.debug) != 1: job_ref = server_service.startScanPatchPolicyCompliance( filtered_refs)
sys.path.append("/opt/opsware/agent/pylibs") #sys.path.append("/opt/opsware/pylibs") from pytwist import * from pytwist.com.opsware.search import Filter # Check for the command-line argument. if len(sys.argv) < 2: print 'You must specify part of the username as the search target.' # print "Example: " + sys.argv[0] + " " + "opsware.com" sys.exit(2) #print 'Host:', sys.argv[1] # Construct a search filter. role = sys.argv[1] filter = Filter() filter.expression = 'UserRoleVO.rolespace *=* %s' % role # Create the TwistServerobject. ts = twistserver.TwistServer() # Authenticate by passing an SA user name and password. try: ts.authenticate("jgoodman","svvs1234") except: print "Authentication failed." sys.exit(2) # Get a reference to ServerService. users = ts.fido.UserRoleService.findUserRoleRefs(filter) #servers = serverservice.findServerRefs(filter)
def set_role(self, role): filter = Filter() filter.expression = 'UserRoleVO.rolename =* %s' % role self.roles += self.ts.fido.UserRoleService.findUserRoleRefs(filter) if len(self.roles) == 0: raise NoSuchRole, role
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())
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)
import re argsa = 'sudo rm -rf /usr/AIR/tmp/audit_result*; sudo rm -rf /tmp/audit_result*; sudo rm -rf /usr/AIR/tmp/audits/*' out = os.system(argsa) rep = open('/usr/AIR/tmp/luigi_sa_data_load.rslta','w') print>>rep, '<br</style><section class="intro" id="zen-intro" align="center"><div align=center>' print>>rep, '<table border=1><tr><th>Audit File</th><th>Status</th></tr>' rep.close() sys.path.append("/opt/opsware/agent/pylibs") from pytwist import * from pytwist.com.opsware.compliance.sco import * from pytwist.com.opsware.search import Filter from pytwist.com.opsware.compliance.sco import AuditResultRef filter = Filter() filter.expression = 'AuditResultVO.name *=* "%s"' % ('') ts = twistserver.TwistServer() serverservice = ts.compliance.sco.AuditResultService # Authenticate by passing an SA user name and password. #auditrefid = sys.argv[1] try: ts.authenticate("jgoodman","svvs1234") except: print "Authentication failed." sys.exit(2) ref = serverservice.findAuditResultRefs(filter) print ref
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)
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: server_service = ts.server.ServerService server_script_service = ts.script.ServerScriptService device_group_service = ts.device.DeviceGroupService auth_service = ts.fido.AuthorizationService swps = ts.swmgmt.SoftwarePolicyService wpps=ts.swmgmt.WindowsPatchPolicyService except: print "Error initializing services to HPSA" sys.exit(2) filter = Filter() filter.expression = opts.filter print filter policies = wpps.findWindowsPatchPolicyRefs(filter) for policy in policies: print long(policy.id) wppvo=wpps.getWindowsPatchPolicyVO(policy) print "Clearing %s" % wppvo.name if (len(wppvo.associatedServers)!=0): servers=wppvo.associatedServers wpps.detachFromPolicies([policy],servers) if (len(wppvo.associatedDeviceGroups)!=0): device_groups=wppvo.associatedDeviceGroups wpps.detachFromPolicies([policy],device_groups) if(int(opts.delete) == 1): print "Deleting %s" % wppvo.name
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:
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 patchWhiteList=None if opts.whitelist:
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 role_acls.append(access_acl)
from pytwist import * from pytwist.com.opsware.search import Filter from pytwist.com.opsware.script import ServerScriptJobArgs # Create a TwistServer object. ts = twistserver.TwistServer() # Authenticate by passing an SA username and password try: ts.authenticate('admin','opsware_admin') except: print "Authentication failed." sys.exit(2) # Construct a search filter. filter = Filter() filter.expression = 'ServerVO.name *=* "%s"' % 'rhel55' filter.objectType = 'device' # Get a reference to ServerService. serverservice = ts.server.ServerService # Perform the search, returning server references. serverRef = serverservice.findServerRefs(filter) print "-------server %s" % serverRef # Contruct a search filter. filter.expression = 'ServerScriptVO.name *=* "%s"' % 'hello world' filter.objectType = 'server_script' # Get a reference to ScriptService. scriptservice = ts.script.ServerScriptService
auth_service=ts.fido.AuthorizationService except: print "Error initializing services to HPSA" sys.exit(2) script_ref=ServerScriptRef(long(opts.script)) script_vo=server_script_service.getServerScriptVO(script_ref) if script_vo.codeType in ['BAT','VBS','PS1']: platform_filter="device_platform_name CONTAINS Win" else: platform_filter="device_platform_name NOT_CONTAINS Win" server_filter = Filter() print opts.filter server_filter.expression="(%s)&(%s)" % (opts.filter,platform_filter) print server_filter.expression server_refs=server_service.findServerRefs(server_filter) server_array=[] for srv in server_refs: server_array.append(srv) filtered_refs=auth_service.filterSingleTypeResourceList(OperationConstants.EXECUTE_SERVER_SCRIPT, server_array) ssja=ServerScriptJobArgs() ssja.targets=filtered_refs ssja.timeOut=3600 if opts.args: ssja.parameters=opts.args
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 ""