Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)
edited by

I am able to send one variable (the ip) as a part of my command with the following code:

iplist

8.8.8.8

1.1.1.1

code for the 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 a 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 a 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 my ip's need to be separate variables.

How can I append the x number add ip variables to the cmd?

1 Answer

0 votes
by (36.8k points)

You need:

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

This will append a each IP in data1 to cmd as the unique item at a 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 the data1.

Want to be a master in Data Science? Enroll in this Data Science Courses

Related questions

Browse Categories

...