Unix SSH:在两台服务器上不同路径下查找文件
刚好之前我也遇到过类似的需求,不想写一堆if-else搞得代码乱糟糟的,给你几个优雅的通用方案,都是实际工作里验证过的:
方案1:用配置映射表(脚本内定义)
核心思路是把服务器和对应路径的映射关系提前定义好,脚本直接根据当前服务器标识取对应的路径,完全不需要判断分支。
如果用Bash脚本的话,可以用关联数组实现:
#!/bin/bash # 定义服务器-路径映射表 declare -A server_search_paths=( ["serverA"]="/data/app/logs" ["serverB"]="/var/www/html/static" ) # 获取当前服务器的主机名(也可以用自定义标识,比如环境变量) current_host=$(hostname) # 校验当前服务器是否有配置 if [[ -z "${server_search_paths[$current_host]}" ]]; then echo "Error: No search path configured for server $current_host" exit 1 fi # 执行find命令 find "${server_search_paths[$current_host]}" -type f -name "*.txt"
后续新增服务器的话,只需要在映射表里加一行键值对就行,脚本逻辑完全不用改,扩展性拉满。
方案2:本地配置文件解耦
如果不想把路径写死在脚本里,可以让每台服务器自己存一个配置文件,脚本只负责读取这个文件的内容执行命令。
比如在每台服务器上创建/etc/find_search_path.conf,里面只写对应路径:
serverA的文件内容:/data/app/logs
serverB的文件内容:/var/www/html/static
然后脚本写成这样:
#!/bin/bash # 读取本地配置文件中的路径 search_path=$(cat /etc/find_search_path.conf) # 校验配置是否存在 if [[ -z "$search_path" ]]; then echo "Error: Search path not set in /etc/find_search_path.conf" exit 1 fi # 执行find命令 find "$search_path" -type f -name "*.txt"
这种方式脚本和服务器配置完全解耦,脚本可以在所有服务器上通用,后续新增服务器只需要创建对应的配置文件即可。
方案3:用自动化运维工具批量管理
如果是批量管理多台服务器的场景,用Ansible这类工具会更省心,完全不需要自己写判断逻辑。
首先在Ansible的inventory文件里给每台服务器定义专属变量:
[my_servers] serverA ansible_host=192.168.1.10 search_path=/data/app/logs serverB ansible_host=192.168.1.11 search_path=/var/www/html/static
然后写一个简单的playbook:
- name: Execute find command on target servers hosts: my_servers tasks: - name: Run find to search for txt files command: find {{ search_path }} -type f -name "*.txt" register: find_output - name: Print search results debug: var: find_output.stdout_lines
执行playbook的时候,Ansible会自动把对应服务器的search_path变量代入命令,完全不用手动处理分支判断,还能批量执行和收集结果。
内容的提问来源于stack exchange,提问作者anonymous
相关产品推荐
相关产品推荐

