Application of Python scripts in Linux server maintenance - specific code examples
Abstract:
With the development of Internet technology, the Linux operating system is used in server maintenance Played a very important role. This article explains how to use Python scripts to automate common tasks in Linux server maintenance to increase efficiency. At the same time, we provide some specific code examples to explain how to write these scripts using Python.
import shutil import datetime # 设置源文件和目标目录 source_dir = '/var/www/html' target_dir = '/backup' # 在目标目录中创建以当前日期为名称的子目录 current_date = datetime.datetime.now().strftime("%Y%m%d") target_path = target_dir + '/' + current_date os.makedirs(target_path) # 复制源目录到目标目录中 shutil.copytree(source_dir, target_path)
The above code uses the copytree() function in the shutil library to copy files and subdirectories in the source directory to the target directory. . By getting the current date and using it as a subdirectory name, you can easily manage and differentiate backup data of different dates.
import os import psutil # 获取系统负载平均值和内存使用情况 avg_load = os.getloadavg() mem_usage = psutil.virtual_memory() # 打印监控结果 print("系统负载:", avg_load) print("内存使用情况:", mem_usage)
The os and psutil libraries are used in the above code to obtain the system load average by calling the corresponding functions. and memory usage. By printing these monitoring results, you can understand the running status of the server at any time.
import os import glob # 定义日志文件目录和最大保留天数 log_dir = '/var/log' max_days = 30 # 获取当前日期 current_date = datetime.datetime.now() # 遍历日志文件并删除过期的文件 for file_path in glob.glob(log_dir + '/*.log'): file_name = os.path.basename(file_path) file_date_str = file_name.split('.')[0] file_date = datetime.datetime.strptime(file_date_str, "%Y%m%d") # 计算文件的存储天数 delta = current_date - file_date file_age = delta.days # 如果文件的存储天数超过最大保留天数,则删除 if file_age > max_days: os.remove(file_path)
In the above code, the storage directory and maximum retention days of the log files are first defined. Then, calculate the number of days the file has been stored by looping through the log file and parsing the date information in the file name. If a file is stored for more than the maximum retention days, the file is deleted.
The above is the detailed content of Application of Python script operations in Linux server maintenance. For more information, please follow other related articles on the PHP Chinese website!