Linux Shell脚本:如何检测NFS挂载点(或服务器)已经死了?

夏期劇*_*期劇場 7 linux bash shell nfsclient nfs

通常在NFS客户端上,如何通过使用Bash Shell脚本来检测服务器端Mounted-Point或DEAD

通常我这样做:

if ls '/var/data' 2>&1 | grep 'Stale file handle';
then
   echo "failing";
else
   echo "ok";
fi
Run Code Online (Sandbox Code Playgroud)

但问题是,当特别是NFS服务器完全死机或停止时,即使是ls命令,在客户端进入该目录也会被绞死或死亡.手段,上面的脚本不再可用.

有没有办法再次检测到这个?

Vil*_*lle 10

"stat"命令是一种更简洁的方式:

statresult=`stat /my/mountpoint 2>&1 | grep -i "stale"`
if [ "${statresult}" != "" ]; then
  #result not empty: mountpoint is stale; remove it
  umount -f /my/mountpoint
fi
Run Code Online (Sandbox Code Playgroud)

此外,您可以使用rpcinfo来检测远程nfs共享是否可用:

rpcinfo -t remote.system.net nfs > /dev/null 2>&1
if [ $? -eq 0 ]; then
  echo Remote NFS share available.
fi
Run Code Online (Sandbox Code Playgroud)

新增2013-07-15T14:31:18-05:00:

我进一步研究了这个问题,因为我还在研究需要识别过时挂载点的脚本.灵感来自其中一个回复 "是否有一种检测陈旧NFS挂载的好方法",我认为以下可能是检查bash中特定挂载点陈旧性的最可靠方法:

read -t1 < <(stat -t "/my/mountpoint")
if [ $? -eq 1 ]; then
   echo NFS mount stale. Removing... 
   umount -f -l /my/mountpoint
fi
Run Code Online (Sandbox Code Playgroud)

如果stat命令由于某种原因挂起,则"read -t1"构造可靠地超出子shell.

新增2013-07-17T12:03:23-05:00:

尽管read -t1 < <(stat -t "/my/mountpoint")有效,但当挂载点过时时似乎没有办法将其错误输出静音.> /dev/null 2>&1在子shell中添加或在命令行的末尾添加会破坏它.使用简单的测试:if [ -d /path/to/mountpoint ] ; then ... fi也可以使用,在脚本中可能更好.经过大量测试,这是我最终使用的.

新增2013-07-19T13:51:27-05:00:

回答我的问题" 如何使用带有stat的读取超时? "提供了有关在目标不可用时静音stat(或rpcinfo)输出的更多详细信息,并且命令会在它超时之前挂起几分钟拥有.虽然[ -d /some/mountpoint ]可用于检测陈旧的挂载点,但rpcinfo没有类似的替代方法,因此使用read -t1重定向是最佳选择.子shell的输出可以用2>& -静音.以下是CodeMonkey响应的示例:

mountpoint="/my/mountpoint"
read -t1 < <(stat -t "$mountpoint" 2>&-)
if [[ -n "$REPLY" ]]; then
  echo "NFS mount stale. Removing..."
  umount -f -l "$mountpoint"
fi
Run Code Online (Sandbox Code Playgroud)

也许现在这个问题得到了充分的回答:).

  • 很好的答案.我看过`read -t1 <<(stat -t"$ MOUNT_DIR"2>& - )`提供的返回值为`142`.这样做`[!$?-eq 0]`作为测试可能更好. (3认同)
  • 另一点:`read -t1 <<(stat -t"$ mountpoint"2>& - )`将保留一个打开的文件句柄(或类似)到已安装的文件夹.因此,如果不使用`-l`标志,mount选项将失败.您可以使用`timeout 1 stat -t"$ mountpoint">/dev/null`代替.这将杀死`stat`命令,因此杀死它的打开文件句柄. (3认同)