Curl Password

Using cURL with a username and password? – Stack Overflow

This is MUCH more than the OP asked for, but since this is a top result for securely passing passwords to curl, I’m adding these solutions here for others who arrive here searching for that.
NOTE: -s arg for read command is not POSIX, and so is not available everywhere, so it won’t be used below. We will use stty -echo and stty echo instead.
NOTE: All bash variables below could instead be declared as locals if in a function, rather than unsetting.
NOTE: perl is pretty generally available on all systems I’ve tried due to it being a dependency for many things, whereas ruby and python are not, so using perl here. If you can guarantee ruby/python where you’re doing this, you can replace the perl command with their equivalent.
NOTE: Tested in bash 3. 2. 57 on macOS 10. 14. 4. Some small translation may be required for other shells/installs.
Securely prompt a user for a (reusable) password to pass to curl. Particularly useful if you need to call curl multiple times.
For modern shells, where echo is a built-in (check via which echo):
url=”
printf “Username: ”
read username
printf “Password: ”
stty -echo # disables echoing user input, POSIX equivalent for ‘read -s’
read pass
printf “\n” # we need to move the line ahead
stty echo # re-enable echoing user input
echo ${pass} | sed -e “s/^/-u ${username}:/” | curl –url “${url}” -K-
unset username
unset pass
For older shells, where echo is something like /bin/echo (where whatever it echos can be seen in the process list):
THIS VERSION CANNOT REUSE THE PASSWORD, see lower down instead.
perl -e ‘
my $val=;
chomp $val;
print STDERR “\n”; # we need to move the line ahead, but not send a newline down the pipe
print $val;
‘ | sed -e “s/^/-u ${username}:/” | curl –url “${url}” -K-
If you happen to need to store the password temporarily to a file, to re-use it for multiple commands before clearing it (say because you’re using functions for code re-use and don’t want to repeat code and can’t pass the value around via echo). (Yes, these are a little contrived looking in this form not being functions in different libraries; I tried to reduce them to the minimum code needed to show it. )
When echo is built-in (this is especially contrived, since echo is a built-in, but provided for completeness):
filepath=”$(mktemp)” # random path, only readable by current user
echo “${pass}” > “${filepath}”
cat “${filepath}” | sed -e “s/^/-u ${username}:/” | curl –url “${url}” -K-
rm “${filepath}” # don’t forget to delete the file when done!!
When echo is something like /bin/echo:
$(perl -e ‘
open(my $fh, “>”, $ARGV[0]) or die “Could not open file \”$ARGV[0]\”” $\! “”;

Frequently Asked Questions about curl password

Leave a Reply

Your email address will not be published. Required fields are marked *