用于在我的LAN中安装PC的Bash脚本

时间:2013-01-26 23:27:54

标签: bash networking ssh mount

我刚刚通过更新我的mount脚本来提高我的Bash技能,我想与世界分享它。如果您有任何想法,请在此处发布。

这是我的scipt:

#!/bin/bash

SDIR="/"
DIR="/home/MyUsername/fusessh/MyNetworkPC"
FMGR='thunar'
USER='MyUsername'
PASS='MyPassword'
IP[0]='192.168.0.100'
IP[1]='192.168.0.101'
IP[2]='192.168.0.102'
IP[3]='192.168.0.103'
PORT='-p 22'


if [ "$(ls -A $DIR)" ]; then
  echo "$DIR is not Empty. And so it will be unmounted..."
  fusermount -u $DIR
else
  CURRENTIP=0
  CONNECTED="False"
  while [ "$CONNECTED" = "False" ] && [ $CURRENTIP -lt ${#IP[@]} ] ; do
    if echo $PASS | sshfs $PORT -o ServerAliveInterval=15 -o password_stdin $USER@${IP[$CURRENTIP]}:$SDIR $DIR > /dev/null; then
      echo "Mounted ${IP[$CURRENTIP]}:$SDIR to $DIR"
      CONNECTED="True"
      $FMGR $DIR &
    else
      echo "Could not mount ${IP[$CURRENTIP]}:$SDIR to  $DIR" 
      let CURRENTIP+=1
    fi 
  done
fi

exit 0

1 个答案:

答案 0 :(得分:1)

这是一个实用且方便的脚本!这是一个略微修改的版本,注释了一些关于您可能选择合并的更改的注释:

#!/bin/bash

sdir="/"
dir="/home/MyUsername/fusessh/MyNetworkPC"
fmgr='thunar'
#USER is also a builtin variable,
#lowercase avoids overriding/confusing these
user='MyUsername'
pass='MyPassword'
ips[0]='192.168.0.100'
ips[1]='192.168.0.101'
ips[2]='192.168.0.102'
ips[3]='192.168.0.103'
port='-p 22'


# Instead of toggling, let the user decide when to mount/umount
# This makes behavior more predictable
if [ "$1" == "-u" ]; then
  # Quoting $dir ensures filenames with spaces still work
  fusermount -u "$dir"
else
  mounted=0
  # We can loop over IPs without keeping a counter
  for ip in "${ips[@]}"
  do
    # echo has some issues when e.g. $PASS is '-n'
    if printf "%s\n" "$PASS" | sshfs $PORT -o ServerAliveInterval=15 -o password_stdin "$user@$ip:$sdir" "$dir" > /dev/null; then
      echo "Mounted $ip:$sdir to $dir"
      $fmgr "$dir" &
      mounted=1
      break
    else
      echo "Could not mount $ip:$sdir to $dir"
      mounted=0
    fi
  done

  if ! (( mounted ))
  then
      echo "Couldn't mount. Sorry!"
      exit 1 # Exit with failure if we can't mount any dir
  fi
fi

# With no explicit 'exit 0' here, the default
# return value is that of the last executed command.
# If fusermount -u fails, the script will now signal this