0

I am trying to construct a command which includes a a variable containing IP addresses to a subprocess but the variable is not passed.

iplist

8.8.8.8
1.1.1.1

code

with open('iplist', 'r', encoding="utf-8") as f:
    data = f.read()
    print(data)
    cmd = ['./mmdbinspect', '--db', '/usr/local/var/GeoIP/GeoLite2-City.mmdb', '$data']
    result = subprocess.run(cmd, stdout=subprocess.PIPE)
    print(result.stdout)

output

8.8.8.8
1.1.1.1
2020/11/01 10:06:13 could not get records from db /usr/local/var/GeoIP/GeoLite2-City.mmdb: $data is not a valid IP address
b''
pablo808
  • 637
  • 1
  • 8
  • 21
  • 1
    f.read() will read entire file as one string so u need to use readlines() then iterate through those lines. –  Oct 31 '20 at 23:18
  • 1
    You don't want to pass `'$data'` to `subprocess.run`. If `data` is the string `'1.1.1.1'`, then you just want `data`. No dollar sign. No quotes. You want the contents of the variable `data` to be in the array. – Frank Yellin Oct 31 '20 at 23:20
  • Your shell obviously has no idea what variables you have used in your Python program, any more than it knows what variable names are used in the C source files for Bash itself. – tripleee Oct 12 '21 at 11:07

3 Answers3

3

Something like

with open('iplist', 'r', encoding="utf-8") as ip_file:
    for ip in ip_file:
      cmd = ['./mmdbinspect', '--db', '/usr/local/var/GeoIP/GeoLite2-City.mmdb', ip.strip()]
      result = subprocess.run(cmd, stdout=subprocess.PIPE)
      print(result.stdout)
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
1

Use: cmd = ['./mmdbinspect', '--db', '/usr/local/var/GeoIP/GeoLite2-City.mmdb', data]

data is a variable name.

$data is used on other languages (like PHP).

zvi
  • 3,677
  • 2
  • 30
  • 48
1

CYREX pointed me in right direction. Thank you.

Final code below

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)
pablo808
  • 637
  • 1
  • 8
  • 21
  • 1
    exactly, my code was missing the strip method, anyway, most important u solved it. regards. –  Oct 31 '20 at 23:34