如何使用Shell脚本从多个服务器和路径中删除多个文件?

oxcyiej7  于 2023-10-23  发布在  Shell
关注(0)|答案(1)|浏览(87)

编写一个shell脚本,从多个文件夹和服务器中删除多个文件,每次SSH到不同的服务器。服务器名称和文件路径的列表应来自输入文件。删除文件后,它应该写入一个输出文件,其中包含所有已删除的文件以及路径和服务器名称沿着。
我试着从一个文本文件中输入服务器名称和路径,并试图读取它。

pvcm50d1

pvcm50d11#

#!/bin/bash

# Input file containing servers and paths
input_file="servers_and_paths.txt"

# List of filenames to delete (separated by space)
files_to_delete="log4j-1.2.13.jar file2.txt file3.txt"

# Output log file
output_log="deleted_files.log"
not_found_log="not_found_files.log"

# Loop through each line in the input file
while IFS= read -r line
do
# Extract server and directory path from the line
server=$(echo "$line" | awk '{print $1}')
directory=$(echo "$line" | awk '{print $2}')

# Check if SSH connection is already established
if ! ssh -q "$server" "exit"; then
    echo "Connecting to $server..."
    
    # Loop through each file in the list and attempt deletion
    for file in $files_to_delete
    do
        # Check if the file exists in the specified directory 
path
        if ssh "$server" "[ -f \"$directory/$file\" ]"; then
            # Delete the file and log the deletion to the output 
log file
            ssh "$server" "rm \"$directory/$file\"" && echo 
"$file deleted from $server:$directory" >> "$output_log"
        else
            echo "$file not found in $server:$directory"
            # Log the missing file information to the not found 
log file
            echo "$file not found in $server:$directory" >> 
"$not_found_log"
        fi
    done
else
    echo "Already connected to $server, skipping..."
fi
done < "$input_file"

相关问题