0

I am trying to append line to an existing file owned by root and I have to do this task with about 100 servers. So I created servers.txt with all the IPs and the ntp.txt file which will have the lines that I need to append. I am executing the following script and I am not achieving what I am trying to. Can someone please suggest what needs to be corrected?

!/bin/bash
servers=`cat servers.txt`;
for i in $servers;
do
  cat ntp.txt | ssh root@${i} sudo sh -c "cat >>ntp.conf""
done
Paulie-C
  • 1,674
  • 1
  • 13
  • 29
Sri
  • 1

1 Answers1

1

Here are some issues; not sure I found all of them.

  1. The shebang line lacks the # which is significant and crucial.
  2. There is no need to read the server names into a variable, and in addition to wasting memory, you are exposing yourself to a number of potential problems; see https://mywiki.wooledge.org/DontReadLinesWithFor
  3. Unless you specifically require the shell to do whitespace tokenization and wildcard expansion on a value, put it in double quotes (or even single quotes, but this inhibits variable expansion, which you still want).
  4. If you are logging in as root, no need to explicitly sudo.
  5. ssh runs a shell for you; no need to explicitly sh -c your commands.
  6. On the other hand, you want to avoid running a root shell if you can. A common way to get to append to a file without having to spawn a shell just to be able to redirect is to use tee -a (just drop the -a to overwrite instead of append). Also printing the file to standard output is an undesired effect (some would say the main effect rather than side effect of tee but let's just not go there) so you often redirect to /dev/null to avoid having the text also spill onto your screen.
  7. You probably want to avoid a useless use of cat if only just to avoid having somebody point out to you that it's useless.
#!/bin/bash
while read -r server; do
do
  ssh you@"$server" sudo tee -a /etc/ntp.conf <ntp.txt >/dev/null
done <servers.txt

I changed the code to log in as you but it's of course something you will need to adapt to suit your environment. (If you log in as yourself, you usually just ssh server without explicitly specifying a user name.)

As per your comment, I also added a full path to the destination file /etc/ntp.conf

A more disciplined approach to server configuration is to use something like CFengine2 to manage configurations.

tripleee
  • 175,061
  • 34
  • 275
  • 318