简体   繁体   中英

Passing Variable with Special characters as password breaks bash script. How do I Sanitize special characters in bash?

I am looking for a solution to sanitizing variables in my bash password change script.

The script below is working, however I have found that some "Special Characters" will break my script. I am not controlling at the moment what Characters are being passed through. I am either looking to sanitize the variables before passing them through, or pushing the variables as a whole untouched. I have tried using '${PASS}' in place of "${PASS}" however the script would not complete when this was the case.

I would appreciate any recommendations anyone could offer. I have tried searching for the answer to this question before posting but didn't find anything relative so i am sorry if this has been answered elsewhere.

#!/bin/bash

# Two variables are passed, Username and new Password. 

USERNAME=$1
PASS=$2

expect << EOF
spawn passwd ${USERNAME}
expect "Enter new UNIX password:"
send "${PASS}\r"
expect "Retype new UNIX password:"
send "${PASS}\r"
expect eof;
EOF

expect << EOF
spawn htdigest /.passwd "Authenticated Users" ${USERNAME}
expect "New password:"
send "${PASS}\r"
expect "Re-type new password:"
send "${PASS}\r"
expect eof;
EOF

expect << EOF
spawn htpasswd /squiddb ${USERNAME}
expect "New password:"
send "${PASS}\r"
expect "Re-type new password:"
send "${PASS}\r"
expect eof;
EOF

Thank you in advance!

Send the username and password to the expect scripts via command-line arguments to expect instead. As done now, a double quote would confuse expect since the here-to document is interpolated fully before sent to expect's stdin.

A password like 'hej"' without the single quotes would lead to a send command for expect looking like this:

send "hej"\\r"

expect will not enjoy that.

You can access the argument via argv, beware of quoting. Do not that you will expose the username and password to anyone doing "ps" on that box if you pass them as arguments on the command line to expect. But you already do that when calling the script in the question...

Why not use the Expect shell directly for doing this.

#!/usr/bin/expect

set timeout 20
set user [lindex $argv 0]
set password [lindex $argv 1]

spawn passwd $user
expect "Enter new UNIX password:"
send "$password\r";
expect "Retype new UNIX password:"
send "$password\r";
wait 1

spawn htdigest /.passwd "Authenticated Users" $user
expect "New password:"
send "$password\r"
expect "Re-type new password:"
send "$password\r"
wait 1

spawn htpasswd /squiddb $user
expect "New password:"
send "$password\r"
expect "Re-type new password:"
send "$password\r"

exit 0

Execute the above like

./SCRIPTNAME.exp user password

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM