Linux系统自动挂载服务

avatar 2025年9月11日18:57:41 评论 48 次浏览

我的环境是在kubernetes的宿主机里挂载里共享目录,然后pod通过HostPath使用本地的共享目录,至于原因是因为pod无法直接使用已经在使用的共享目录,有掉绕,不过没关系,意思没有改变.为了方便我的系统启动时可以直接挂载共享目录,所以写了一个服务,自动检查,然后自动挂载,先看一下我的需求:

   mount -t cifs //10.32.128.44/customs /apps/works/data -o username=wulaoer,password=wulaoer1234
  curlftpfs -o allow_other,user="wulaoer":"wulaoer1234" ftp://10.32.128.33/ /apps/works/wulaoer

我这一个是smb一个是ftp的服务,我想把这两个挂载通过服务的方式自动检查自动挂载,然后系统重启不影响,就需要写一个脚本然后通过服务控制这个脚本,每1分钟检查一次.

1. 挂载脚本

保存到 /usr/local/bin/mount-check.sh

 #!/bin/bash
 # SMB 和 FTP 挂载目录
 MOUNT_SMB="/apps/works/data"
 MOUNT_FTP="/apps/works/wulaoer"
 
 # SMB 挂载
 if ! mountpoint -q $MOUNT_SMB; then
     echo "$(date) - Remounting SMB..."
     mount -t cifs //10.32.128.44/customs $MOUNT_SMB -o username=wulaoer,password=wulaoer1234
 fi
 
 # FTP 挂载
 if ! mountpoint -q $MOUNT_FTP; then
     echo "$(date) - Remounting FTP..."
     curlftpfs -o allow_other,user="wulaoer":"wulaoer1234" ftp://10.32.128.33/ $MOUNT_FTP
 fi

赋予执行权限:

 chmod +x /usr/local/bin/mount-check.sh

2. systemd service

/etc/systemd/system/mount-check.service

 [Unit]
 Description=Check and remount SMB/FTP directories
 After=network-online.target
 Wants=network-online.target
 
 [Service]
 Type=oneshot
 ExecStart=/usr/local/bin/mount-check.sh
 RemainAfterExit=true
 
 [Install]
 WantedBy=multi-user.target

3. systemd timer

/etc/systemd/system/mount-check.timer

 [Unit]
 Description=Periodic check for SMB/FTP mounts
 
 [Timer]
 OnBootSec=1min
 OnUnitActiveSec=1min
 Unit=mount-check.service
 
 [Install]
 WantedBy=timers.target

4. 启动并生效

 systemctl daemon-reload
 systemctl enable --now mount-check.service
 systemctl enable --now mount-check.timer

这样我就不需要担心我的系统重启之后需要收到挂载了,有的说使用定时任务也是一样的,但是定时任务过多就会导致挺乱的,有些环境不允许使用定时任务,这种方式显得比较合适点.

avatar

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: