I am trying to connect to server B from server A using ssh and executing commands using some other user.
However,
when I try searching for a pattern in log file it says "cannot open log file"
below is the sample code
ssh -t user@hostname <<EOF
sudo su - someotheruser
a=`tail -10 /somepath/application.log | awk '/Agent Exited/ { print $3 }'`
if [ $a -eq 0 ]
then
echo "Success"
else
echo "Failure"
fi
EOF
once I run the script,
it says, unable to open "tail........."
I can't stay logged in on server B and run multiple commands.
Best Answer
Think carefully about when each command is executed, where it runs, and what input it receives.
tail
/awk
pipe is executed on the local host, and the variable substitution$a
as well.ssh
command is executed. It receives the expanded here document; these are commands that are executed in the remote shell.sudo
, but possibly (depending on the shell) some of the following lines as well.sudo su - someotheruser
. This runs a shell assomeotheruser
which first reads and executes that user's.profile
, then reads commands from its standard input. The standard input contains whatever the first remote shell did not read, which is somewhat unpredictable (it depends on the shell and how much it happened to read from its input pipe).someotheruser
runs the commands that it read, if any.someuser
executes theif
command (if it's read it).To avoid here document expansion, use quotes around the heredoc marker. To avoid the unholy mixture of standard inputs, use
sh -c …
or be explicit as to what the second remote shell receives as its input.Do you really need to source
someotheruser
's.profile
? If not, usesudo -u someotheruser
. If you do, usesudo -i -u someotheruser
. Ajust your sudoers rule accordingly.Reading the log file is the only thing that requires elevated privileges, so it would make sense to only run the
tail
command assomeotheruser
.You'll make your life a lot easier if you don't mix privilege escalation methods. Instead of using
sudo
to switch fromsomeuser
tosomeotheruser
, use SSH to localhost. Chaining two ssh commands is easy. Set up a key — you can even set up a key that only allows running a specific command liketail -10 /somepath/application.log
. Define an alias in your.ssh/config
to SSH through thesomeuser
account:Then run