0

This question is based on my previous question on creating a command for subprocess. I am able to send one variable (the ip) as part of the command with the following code:

iplist

8.8.8.8
1.1.1.1

code for one ip

with open('iplist', 'r', encoding="utf-8") as f:
    data = f.readlines()
    print(data)
    for line in data:
        ip = line.strip() # strip \n lookup will fail
        cmd = ['./mmdbinspect', '--db', '/usr/local/var/GeoIP/GeoLite2-City.mmdb', ip]
        print(cmd)
        result = subprocess.run(cmd, stdout=subprocess.PIPE)
        print(result.stdout)

I would like to send x number of variables (ip) to this command like so:

cmd = ['./mmdbinspect', '--db', '/usr/local/var/GeoIP/GeoLite2-City.mmdb', '8.8.8.8', '1.1.1.1']

code for x ip's

with open('iplist', 'r', encoding="utf-8") as f:
    data = f.readlines()
    print(data)
    data1 = [ip.strip() for ip in data] # list comprehension - remove \n from each item in the list
    print(data1)
    data2 = ' '.join(data1)
    print(data2)
    cmd = ['./mmdbinspect', '--db', '/usr/local/var/GeoIP/GeoLite2-City.mmdb', data2]
    print(cmd)
    result = subprocess.run(cmd, stdout=subprocess.PIPE)
    print(result.stdout)

output

['./mmdbinspect', '--db', '/usr/local/var/GeoIP/GeoLite2-City.mmdb', '8.8.8.8 1.1.1.1']
2020/11/01 13:49:38 could not get records from db /usr/local/var/GeoIP/GeoLite2-City.mmdb: 8.8.8.8 1.1.1.1 is not a valid IP address

As you can see the ip's need to be seperate variables.

How do I append x number additional ip variables to cmd?

pablo808
  • 637
  • 1
  • 8
  • 21

1 Answers1

1

I think you want:

cmd = ['./mmdbinspect', '--db', '/usr/local/var/GeoIP/GeoLite2-City.mmdb', *data1]

This will append each IP in data1 to cmd as a unique item at the end of that list. Here's an illustration:

data1 = ['8.8.8.8', '1.1.1.1']
cmd = ['./mmdbinspect', '--db', '/usr/local/var/GeoIP/GeoLite2-City.mmdb', *data1]
print(cmd)

Result:

['./mmdbinspect', '--db', '/usr/local/var/GeoIP/GeoLite2-City.mmdb', '8.8.8.8', '1.1.1.1']

This will work for any number of IPs in data1.

CryptoFool
  • 21,719
  • 5
  • 26
  • 44
  • Thank you for the explanation. I didn't realise I could use *data1. I was over thinking, wondering if I had to iterate, join then append cmd. – pablo808 Nov 01 '20 at 03:48