我做错了什么?尝试在ssh到一台服务器后为多个路径执行chmod o-w
。文件1.txt包含两列;一列具有相同的服务器,名为SERVER_hostname,第二列具有不同的路径。我希望脚本将ssh指向特定的服务器主机名,然后使自己成为根用户( toor,sudo ),然后将命令chmod运行到第二列中的不同路径。
#!/bin/bash
read -r -a server < 1.txt
echo "${server[0]}"
echo "ssh -oBatchMode=yes -q "$(echo "${server[0]}")" '"$(cat 1.txt | awk '{print " sudo eksh ; \ chmod o-w " $NF";"}')"'" | sh
./254.sh
SERVER_hostname
awk: warning: escape sequence `\ ' treated as plain ` '
chmod: changing permissions of ‘/etc/nginx-controller/agent.configurator.conf.default’: Operation not permitted
chmod: changing permissions of ‘/etc/nginx-controller/agent.controller.conf.default’: Operation not permitted
chmod: changing permissions of ‘/etc/nginx-controller/copyright’: Operation not permitted
chmod: missing operand after ‘o-w’
Try 'chmod --help' for more information.
1.txt
SERVER_hostname /etc/nginx-controller/agent.configurator.conf.default
SERVER_hostname /etc/nginx-controller/agent.controller.conf.default
SERVER_hostname /etc/nginx-controller/copyright
发布于 2022-08-16 05:03:43
实现这一目标有多种方法。但是由于ssh
的使用,它们都有一些窍门。在循环或复杂构造中使用ssh时,您必须始终意识到ssh
会消耗您的/dev/stdin
。
实现的最快方法是使用while循环对ssh执行多次调用来读取文件(请参阅BashFAQ#001)。然而,我们强制ssh
使用/dev/null
作为输入流。这样,我们就可以避免while循环中断:
while read -r host file; do
[ "$host" ] || continue
[ "$file" ] || continue
</dev/null ssh -oBatchMode=yes -q "${host}" -- sudo eksh -c "chmod o-w -- ${file}"
done < file.txt
上面的方法将执行对ssh的多个调用,可能不是最有效的方法。您可以使用数组来构建包含命令参数的命令(请参阅BashFAQ#050)。对于OP,这将是不同的文件名:
file_list=()
while read -r h f; do [ "$f" ] && file_list+=( "${f}" ); [ "$h" ] && host="$h"; done < file.txt
ssh -oBatchMode=yes -q "${host}" -- sudo eksh -c "chmod o-w -- ${file_list[@]}"
但是,如果你的论点列表太长,这里也有一个问题。所以现在的诀窍是直接在ssh上使用xargs
。你可以这样做:
file_list=()
while read -r h f; do [ "$f" ] && file_list+=( "${f}" ); [ "$h" ] && host="$h"; done < file.txt
printf "%s\n" "${file_list[@]}" | ssh "$host" "cat - | sudo eksh -c 'xargs chmod o-w --'"
注意:由于某种原因,命令ssh "$host" sudo eksh -c 'xargs chmod o-w --'
无法工作。这就是我们引入cat -
的原因。
https://stackoverflow.com/questions/73372281
复制相似问题