Need to pass object in a python array in bash

Viewed 82

I am trying to get the response code for three sites using the below python code snippet. But wondering how I can parse each object in the array to pass through the for loop within the curl call.

import os

servers = ["google", "yahoo", "nonexistingsite"]
for i in range(len(servers)):
    print(os.system('curl --write-out "%{http_code}\n" --silent --output'
                    ' /dev/null "https://servers[i].com"'))

With the above code, it's not getting passed through servers[i].

3 Answers

You need to perform string formatting, like:

import os

servers = ["google", "yahoo", "nonexistingsite"]
for server in servers:
  print(os.system('curl --write-out "%{{http_code}}\\n" --silent --output /dev/null "https://{}.wellsfargo.com"'.format(server)))

The above can however still go wrong, if for example the servers contain quotes, etc.

It might be better to here use subprocess.run and pass it a list of parameters, like:

servers = ["google", "yahoo", "nonexistingsite"]
for server in servers:
    p = subprocess.run(
        [
            'curl'
            '--write-out',
            '%{http_code}\\n',
            '--silent',
            '--output'
            '/dev/null',
            'https://{}.wellsfargo.com'.format(server)
        ],
        shell=True,
        capture_output=True
    )

Try using Python's string formatting, something like:

"This string uses an %s" %(argument) would become "This string uses an argument"

Something like this:

print(os.system('curl --write-out "%%{http_code}\n" --silent --output /dev/null "https://%s.wellsfargo.com"') % (servers[i])

More here: https://powerfulpython.com/blog/python-string-formatting/

Just use the requests library instead of shelling out to run curl:

for s in servers:
    resp = requests.get(s)
    print(resp.status_code)

Since you don't care about the body of the response, only whether it responds, you could save bandwidth by using the head function instead of get to retrieve only the headers from the server.

Related