# Linux通过fstab挂载文件,开机自动挂载
注意:示例脚本均为挂载windows文件,挂载其他文件系统请修改正确的文件系统类型
# 编辑fstab文件
vim /etc/fstab
# 增加以下内容
//192.168.1.10/Datas /Datas cifs auto, username=username, password=password 0 0
1
2
3
4
2
3
4
# 手动执行挂载
# 执行
mount -a
1
2
2
# 设置定时挂载
如果脚本需要使用root权限执行,则切换到root账户下添加定时任务
# 查看定时任务列表
crontab -l
# 编辑定时任务
crontab –e
# 设置定时挂载
crontab –e #等同于: `vim` `/var/spool/cron/root`
# 每隔1小时挂载一次
0 */1 * * * mount -a
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# mount命令挂载
mount -t cifs -o username=username,password=password //192.168.1.10/Datas /Datas
1
# 2022-06-07更新
为了方便配置多个文件系统挂载,使用python脚本挂载
说明:
脚本使用ping
会导致一些延迟,若时延要求高,可采取心跳检测的方式重写。
umount
和ping
的操作是为了解决远程主机关闭后导致的磁盘IO阻塞的问题,具体表现为df、ls
等命令卡住。
脚本使用环境为ubuntu18.04、python v3.6.9
,使用ubuntu默认的cron包作为定时任务的管理端,如下:
# apt show cron
Package: cron
Version: 3.0pl1-128.1ubuntu1.2
1
2
3
2
3
#!/usr/bin python3
# -*- coding: utf-8 -*-
"""
@Author: flamingo
@Date : 2022-06-01 10:00
@FileName : mount.py
@Description :
远程主机文件挂载脚本,脚本默认5分钟挂载一次,若ping通远程主机则挂载,否则卸载。
忽略重复挂载和卸载不存在的target错误。
示例为挂载windows系统文件,若需要挂载其他系统请修改mount_script_template参数。
注意:此脚本需要以root用户运行。
python版本为v3.6.9,高版本subprocess库API不同
建议创建目录/root/mount/,将脚本移动到此目录,然后执行以下操作。
1、初次运行初始化命令 `python3 mount.py init`
2、修改初始化后输出的配置文件 `mount.toml`
3、执行安装命令 `python3 mount.py install`
"""
import datetime
import os
import subprocess
from os.path import exists
from sys import argv
from toml import load
example_configuration = '''[[devices]]
name = "LINE1 回流焊1#"
username = "admin"
password = "admin"
source = "//192.168.0.8/Datas"
target = "/home/data/"
'''
configure_file_path = "/root/mount/mount.toml"
log_path = "/root/mount/log"
cron_expression = "*/5 * * * *"
mount_script_template = "mount -t cifs -o username={0},password={1} {2} {3}"
umount_script_template = "umount {0}"
# output debug log to `/tmp/mount.log`
debug = False
def init():
if not os.path.exists(log_path):
os.mkdir(log_path)
if exists(configure_file_path):
log("Configure file already existed.")
return
with open(configure_file_path, 'w', encoding='utf-8') as fw:
fw.write(example_configuration)
log("Initialization successful!")
pass
def install():
write_cron_table()
log("Install successful!")
pass
def load_config():
if not exists(configure_file_path):
log("Mount configure file not found, please run `python3 mount.py init`.")
exit(1)
log("Start to load configure file process.")
with open(configure_file_path, 'r', encoding='utf-8') as fr:
config = load(fr)
configs = []
for conf in config['devices']:
source_split_arr = conf['source'].split('/')
if len(source_split_arr) < 3:
log("Configure file error, ip not found. `source` = {}".format(conf['source']))
exit(1)
ip = source_split_arr[2]
conf['ip'] = ip
configs.append(conf)
return configs
pass
def mount():
configs = load_config()
for i, conf in enumerate(configs):
log(" ----- MOUNT START {0} - {1} ----- ".format(i + 1, conf['name']))
# ping
ping_script = "ping {} -c 1".format(conf['ip'])
log("PING: {}".format(ping_script))
ping_output = subprocess.run(ping_script, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
encoding='utf-8')
log("RETURN CODE: " + str(ping_output.returncode))
log("STDERR: " + ping_output.stderr)
# umount
if ping_output.returncode != 0:
umount_script = umount_script_template.format(conf['target'])
log("UMOUNT: {}".format(umount_script))
output = subprocess.run(ping_script, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
encoding='utf-8')
log("RETURN CODE: " + str(output.returncode))
log("STDOUT: " + output.stdout)
log("STDERR: " + output.stderr)
else:
# mount
mount_script = mount_script_template.format(conf['username'], conf['password'], conf['source'], conf['target'])
log("MOUNT: {}".format(mount_script))
output = subprocess.run(mount_script, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
encoding='utf-8')
log("RETURN CODE: " + str(output.returncode))
log("STDOUT: " + output.stdout)
log("STDERR: " + output.stderr)
log(" ----- MOUNT END {0} - {1} ----- ".format(i + 1, conf['name']))
pass
def log(text_log: str):
now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')
log_file_name = datetime.datetime.now().strftime('%Y-%m-%d.log')
if not os.path.exists(log_path):
os.mkdir(log_path)
full_path = os.path.join(log_path, log_file_name)
suffix = "\n"
if text_log.endswith("\n"):
suffix = ""
formatted_log = "[{0}] {1}{2}".format(now, text_log, suffix)
print(formatted_log)
if not os.path.exists(full_path):
with open(full_path, "w+", encoding='utf-8') as f:
f.close()
with open(full_path, "a+", encoding='utf-8') as f:
f.write(formatted_log)
pass
def clean_log(day):
date = datetime.datetime.now() - datetime.timedelta(days=day)
date_int = int(date.strftime("%Y%m%d"))
list_dirs = os.listdir(log_path)
for dir_item in list_dirs:
path_text = os.path.splitext(dir_item)
if ".log" == path_text[1]:
if int(path_text[0].replace("-", "")) < date_int:
full_path = os.path.join(log_path, dir_item)
try:
os.remove(full_path)
except Exception as e:
log("Clean log file error: {}".format(str(e)))
pass
def write_cron_table():
pwd_script = "pwd"
log("PWD: {}".format(pwd_script))
pwd_output = subprocess.run(pwd_script, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
encoding='utf-8')
log("RETURN CODE: " + str(pwd_output.returncode))
log("STDOUT: " + pwd_output.stdout)
log("STDERR: " + pwd_output.stderr)
if pwd_output.returncode != 0:
log("Run command error: [pwd] " + pwd_output.stderr)
exit(1)
script_path = os.path.join(pwd_output.stdout.replace("\n", ""), "mount.py")
cron_script = '{0} python3 {1}\n'.format(cron_expression, script_path)
if debug is True:
cron_script = '{0} python3 {1} >> /tmp/mount.log 2>&1 \n'.format(cron_expression, script_path)
crontab_record_script = "(crontab -l 2>/dev/null; echo \"{0}\") | crontab -".format(cron_script)
log("CRONTAB RECORD SCRIPT: {}".format(crontab_record_script))
output = subprocess.run(crontab_record_script, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
encoding='utf-8')
log("RETURN CODE: " + str(output.returncode))
log("STDOUT: " + output.stdout)
log("STDERR: " + output.stderr)
if output.returncode != 0:
log("Run command error: [crontab] " + output.stderr)
exit(1)
pass
if __name__ == '__main__':
if len(argv) >= 2:
if argv[1] == "init":
init()
exit(0)
if argv[1] == "install":
install()
exit(0)
mount()
clean_log(7)
exit(0)
pass
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197