Conditions
- h1, h2, and h3 are three Linux hosts that have joined the same Active Directory domain
- Account A and B are both AD account
- B can SSH into all hosts with no password required (Kerberos authentication is setup), and sudo as A (
sudoeris setup so it can run ALL command without password) on each host - A can’t SSH into these hosts directly
/local/path/exist on all hosts- f1 and f2 are created under
/local/path/on h1, and these files are only readable by A - These files can contain multiple lines, double quotes, $
Target
- Create f1 and f2 on h2 and h3 with the same content
My incomplete solution
I come up with the following script, however it has some problems: "" and $ will disappear
- Could you help make my script work as expected
- Is there a better way to achieve my goal?
# src and dest should actually be the same (but on different hosts)
# Since we are doing the test on localhost, they are set to different directories (only accessible by testuser, i.e. account A)
SRC_DIR=/home/testuser
DEST_DIR=/var/tmp/testuser
# For demo purpose. In reality, it should be an array of hosts, i.e. h2, h3
HOSTS=(localhost)
FILES=(f1 f2)
declare -A FILE_TO_CONTENT=([f1]="`sudo -i -u testuser cat /home/testuser/f1`" [f2]="`sudo -i -u testuser cat /home/testuser/f2`")
for h in ${HOSTS[@]}
do
for f in ${FILES[@]}
do
file_content=${FILE_TO_CONTENT[$f]}
echo "$file_content" # The output looks normal
ssh $h "echo \"${file_content}\" | sudo -i -u testuser tee $DEST_DIR/$f " # Double quotes are removed, $dollar disappears
echo "" # Separate output for different files
done
done
The content of f1 and f2
# f1
f1-line 1
f1-line 2
f1-line 3 with "double quote"
f1-line 4 with 'single quote'
f1-line 5 with special char: #hash, $dollar
# f2
f2-line 1
f2-line 2
The output after I run my script (and the output file under /var/tmp/testuser also don't have "" and $)
f1-line 1
f1-line 2
f1-line 3 with "double quote"
f1-line 4 with 'single quote'
f1-line 5 with special char: #hash, $dollar
f1-line 1
f1-line 2
f1-line 3 with double quote
f1-line 4 with 'single quote'
f1-line 5 with special char: #hash,
f2-line 1
f2-line 2
f2-line 1
f2-line 2
ssh $h 'echo "'"${file_content}"'" | sudo -i -u testuser tee '"$DEST_DIR/$f", so the local shell will not touch them since you used double quotes around the remote commandsudo's option-i? I would not put the files' contents into a variable. In the loop you can dosudo -u testuser cat "SRC_DIR/$f" | ssh "$h" sudo -u testuser tee "$DEST_DIR/$f"or with GNUtarand only a loop over the hostssudo -u testuser tar -C "$SRC_DIR" c f1 f2 | ssh "$h" sudo -u testuser tar -C "$DEST_DIR" x. Repeatedly reading the same files will probably be fast due to caching.