How to get ID of target by name?


#1

Hello.

I try to get ID of target object by given name via gmp class like this:

try:
  targets = []

  with gmp:
    gmp.authenticate(username, password)

    targets = gmp.get_targets(filter='name=my-target-name')
    for target in targets.xpath('target'):
      output = target.find('id').text

But i have an error with last string.
Could you tel me how i can get id by name correctly ?


#2

The code looks fine at first sight. Could you paste the error traceback?


#3

Hi.

Here is output

Traceback (most recent call last):
File “./modify_target.py”, line 40, in
output = target.find(‘id’).text
AttributeError: ‘NoneType’ object has no attribute ‘text’

Therefore it doesn’t find “id” data ?
But if a search “name” it works okay


#4

You are trying to access an xml attribute as child element. Target id is an xml attribute. See

https://docs.greenbone.net/API/GMP/gmp-8.0.html#command_get_targets

Could you try

output = target.get('id')

instead?

https://docs.python.org/3/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.get


#5

Yes,

output = target.get('id')

Works fine for me.
Thanks a lot.