3

I want to run a script from my Jump server, have it SSH to a server, then run a command (like rm <file>, top or ls -lsa) then take that output and put it in to a file on my Jump server then move on to the next IP in the list.

I would like to be able to provide the script a list of IP address and have it execute the script on all of them.

So far I have

ssh <IP> 'find ./<Path> -mtime +15 -exec rm <filename> {} \;' > <filename>

But all this does is ssh to the box, run the command and list the info. I need it to run the command, output the data to a file on my jump server and then move on to the next box.

Any suggestions?

Dolyak
  • 109
  • 2
  • 3
  • 8

1 Answers1

2
#! /bin/bash
cd /path/to/ssh_logs || exit 1
for targethost in a b c; do
  log_file="${targethost}/$(date --iso-8601=seconds).log"
  mkdir -p "${targethost}" || { echo "Error: ${targethost}";exit 1; }
  { ssh batchuser@"${targethost}" "$command"; rc=$?;
    echo $'\n'"finished (with exit code ${rc}): $(date --iso-8601=seconds)";
  } >"$log_file" 2>&1
done

Edit 1:

Some explanation required (I also changed details of the script):

  1. In a directory – /path/to/ssh_logs in this example – one subdirectory for each target host is created into which the output files are placed. An alternative is to put all files into the same directory and make the host part of the file name. That's more a matter of taste (for reasonable amounts of files). Thus the first step is to try to change to this directory (and abort if that fails).
  2. for targethost in a b c; do ... ; done is the loop over the hosts. In the example the host names are hard coded in the script. Alternatively you could write them in a text file, one per line or separated by space, and get the names into the script this way: for targethost in $(<targethosts.txt); do
  3. The path of the output file is the subdirectory for that host, the current time stamp and ".log".
  4. The subdirectory is created if it does not exist yet (the script prints the host and aborts if this fails).
  5. The output of two commands is redirected to the file: The ssh call itself and – if you like – the timestamp (including ssh's exit code) immediately after ssh has finished so that you can see from the log how long it took. After stdout of the commands has been redirected to the file, stderr is redirected to stdout so that messages there get to the file, too.
Hauke Laging
  • 90,279
  • +1 I think some comments/explanations would help the OP, though. – Joseph R. Jun 06 '13 at 21:40
  • OK, asking the OP: Is there anything you want explained? The core parts are the for loop which repeats the action for different hosts and the output redirection >"$log_file" 2>&1 – Hauke Laging Jun 06 '13 at 21:52
  • Yes some simple explanation would be great! I think I see what the script is doing. I would put my IPs in /path/to/ssh_logs and my command in $command and the script would work? sending all the data received to log_file? – Dolyak Jun 07 '13 at 12:08