Ofer
Ofer

Reputation: 5209

How to use ssh tail command and write to local file

I'm trying to write a script that reads logs from 3 linux machines and writes the logs (with some kind of prefix) in one file.

My problem is that I can access to the file in order to see it, but when I try to write it doesn't work.

Working code

expect -c "
spawn ssh [email protected] \" tail -f my_file\"
expect { 
   \"*assword\" {send \"PASS\r\";}
}
expect eof 
"

if I add

tail -f >> my_file.log

it doesn't work.

Upvotes: 0

Views: 2847

Answers (3)

user2528891
user2528891

Reputation: 31

This is my solution (Including auto-login) in case you want to use in a Bash script:

#!/bin/bash
FILEPATH=/root/logs/
FILENAME='myfile.log'
SSHPASS=YOUR_PASSWORD sshpass -e ssh -oBatchMode=no USER@IPHOST "tail -f $FILEPATH$FILENAME" > $FILENAME

Press CRTL+C to kill the tail capture.

Upvotes: 0

meuh
meuh

Reputation: 12255

Your command

tail -f filename >> my_file.log

is being run on the remote. So my_file.log is on the remote. To get the output to a local file, move the >> my_file.log to the end of the expect script:

 expect -c "..." >> my_file.log

Upvotes: 1

Flimm
Flimm

Reputation: 150653

First off, I would highly recommend learning how to use SSH with keys so that you don't need a password.

Then, all you need to do is this:

ssh username@server 'tail -f filename' >> my_file.log

Upvotes: 1

Related Questions