Pages

Tuesday, January 22, 2019

SSH + HERE Doc + Var Expansion + Command Output Capture


Go to a remote server and see if folder files are opened:


1. 
export dir=/xxx/yyy/zzz

cat <<HERE > $0.cmd

cd $dir
for x in \$(ls -1)
do
/usr/sbin/lsof +d "$dir" | grep -q "REG.*"\$x
if [ \$? -eq 0 ]; then
echo \$x' is opened'
else
echo \$x' is not opened
fi
done
exit
HERE

ssh -o BatchMode=yes user@host  /bin/sh -s < $0.cmd


rm $0.cmd


2. (sh -c + nested HERE)
export dir=/aaa/bbb/ccc
export file=XXX*

ssh  -T user@host  /bin/sh -c " '
cd $dir
for x in \$(ls -1 $file)
do
/usr/sbin/lsof +d "$dir" | grep -q "REG.*"\$x
if [ \$? -eq 0 ]; then
echo \$x" is opened"
else
echo \$x" is not opened"
sftp user2@host2 << HERE2
  cd /dir
  put xxx

HERE2
fi
done
' "

3. (nested HERE)
ssh -T user@host <<-'HERE'
cd /aaa/bbb/ccc
for x in $(ls -1)
do
lsof +d "/aaa/bbb/ccc" | grep -q "REG.*"$x
if [ $? -eq 0 ]; then
echo $x' is opened'
else 
echo $x' is not opened'
sftp user2@host2 << HERE2
  cd /dir
  put xxx
HERE2
fi
done
exit

HERE