0

I have a simple bash script below that outputs into a file threat info from the domain 1605158521.rsc.cdn77.org. The domain is read from B1Dossier.

#!/bin/bash

baseurl=https://csp.infoblox.com
B1Dossier=/tide/api/data/threats/state/host?host=1605158521.rsc.cdn77.org
APIKey=<REDACTED>
AUTH="Authorization: Token $APIKey"


curl -H "$AUTH" -X GET ${baseurl}${B1Dossier} > /tmp/result

This time, I want the script to get information from multiple domains. For example, I have a file (domfile) with the following domains with each being on a new line:

  • cdn.js7k.com
  • example.org
  • www.hdcctvddns.com

How can I turn my script to execute on each domain from a file (domfle)?

Nina G
  • 269
  • 5
  • 17
  • 1
    How to read for a file, looping on lines: https://mywiki.wooledge.org/BashFAQ/001 – Nic3500 Apr 29 '22 at 18:12
  • Note that you'll want quotes, as in `"${baseurl}${B1Dossier}"`, to prevent surprises if your inputs have spaces. (As a rule, code should be written defensively even when you don't have a specific reason to know it would be a problem to be less careful -- failure to do that is where vulnerabilities come from in the first place). – Charles Duffy May 01 '22 at 13:52

1 Answers1

0

you can use a for loop something like this:

while read -r line; do
  echo "$line"
done < <file_path>

you can also use cat to read the file, and use xargs you can execute any command you want per line. but if used incorrectly can lead to command injection.

If for some reason you need to use this syntax over the for loop. take a look at the comments, and research more about command injection with xargs sh.

cat <file_path> | xargs ...
CY-OD
  • 336
  • 2
  • 8
  • 1
    `xargs -I {} sh -c '...{}...'` has major security problems; if your data being substituted contains, say, `$(rm -rf ~)'$(rm -rf ~)'` (after xargs unescapes it, since you aren't running with `-0` or `-d`) you'll have an extremely bad day. The `while read` loop is the safe approach -- I'd argue it's the only one you should show at all, but _at least_ put it first. – Charles Duffy May 01 '22 at 13:46
  • 1
    Mind, `echo "$line"` is more correct than `echo $line` -- see [I just assigned a variable, but `echo $variable` shows something else!](https://stackoverflow.com/questions/29378566/i-just-assigned-a-variable-but-echo-variable-shows-something-else) – Charles Duffy May 01 '22 at 13:47
  • 1
    (to be clear, it's not `xargs sh` on its own that's unsafe, but _specifically_ `xargs -I {} sh -c '...{}...'`; there are other, safer ways to call sh from xargs, like `xargs -d $'\n' sh -c 'for line in "$@"; do echo "Received line: $line"; done' _`) – Charles Duffy May 01 '22 at 13:50
  • You are correct, updated my answer for future references. thanks. – CY-OD May 01 '22 at 15:06