【问题标题】:ssh to different nodes using shell scripting使用 shell 脚本 ssh 到不同的节点
【发布时间】:2017-03-13 12:25:02
【问题描述】:

我正在使用下面的代码来 ssh 到不同的节点并查找用户是否存在。如果用户不存在,它将创建它。

如果我不使用 ssh,脚本可以正常工作,但如果我使用 ssh,脚本会失败。

如何使用这个脚本遍历不同的节点?

for node in `nodes.txt`
usr=root

ssh $usr@$node 
do
if [ $(id -u) -eq 0 ]; then
    read -p "Enter username : " username
    read -s -p "Enter password : " password
    egrep "^$username" /etc/passwd >/dev/null
    if [ $? -eq 0 ]; then
        echo "$username exists!"
        exit 1
    else
        pass=$(perl -e 'print crypt($ARGV[0], "password")' $password)
        useradd -m -p $pass $username
        [ $? -eq 0 ] && echo "User has been added to system!" || echo "F
ailed to add a user!"
    fi
else
    echo "Only root may add a user to the system"
    exit 2
fi
done

【问题讨论】:

  • 为什么要添加没有主文件夹的用户?尝试在 useradd 命令中创建不带 -m 标志的用户。

标签: linux shell ssh


【解决方案1】:

您的脚本有严重的语法错误。我猜一开始的 for 循环是您尝试添加的,但您在此过程中完全破坏了脚本。

循环遍历文件中的行的语法是

while read -r line; do
    .... # loop over "$line"
done <nodes.txt

(或略微for line in $(cat nodes.txt); do ...但这有多个问题;有关详细信息,请参阅http://mywiki.wooledge.org/DontReadLinesWithFor)。

如果打算实际运行ssh 中的脚本的其余部分,则需要将其传递给ssh 命令。像这样的:

while read -r node; do
   read -p "Enter user name: " username
   read -p -s "Enter password: "
   ssh root@"$node" "
       # Note addition of -q option and trailing :
       egrep -q '^$username:' /etc/passwd ||
       useradd -m -p \"\$(perl -e 'print crypt(\$ARGV[0], \"password\")' \"$password\")" '$username'" </dev/null
done <nodes.txt

当然,您传递给ssh 的命令可以任意复杂,但您会希望避免在 root 特权远程脚本中执行交互式 I/O,并且通常要确保远程命令与可能。

反模式command; if [ $? -eq 0 ]; then ... 很笨拙但很常见。 if 的目的是运行一个命令并检查它的结果代码,所以这是更好,更惯用的写法if command; then ...(如果你只需要@987654336,可以更简洁地写成command &amp;&amp; ...! command || ... @ 或 else 部分,分别是完整的长手 if/then/else 结构)。

【讨论】:

  • 感谢您的回复。问题不在于循环。问题是我无法在 diff 节点上 ssh 并执行脚本中编写的任务。
  • 那么您的问题不清楚/太宽泛。此时明显编辑问题可能是不可取的;也许只是用正确的minimal reproducible example 发布一个新问题,尽管它可能与现有问题重复。
  • 请参阅the Stack Overflow bash tag wiki 了解一些常见的常见问题解答。
【解决方案2】:

也许您应该只通过 ssh 执行远程任务。其余的都在本地运行。

ssh $user@$node egrep "^$username" /etc/passwd >/dev/null

ssh $user@$node useradd -m -p $pass $username

如果您想在所有节点上创建相同的用户,最好在循环之外询问用户名和密码。

【讨论】:

    猜你喜欢
    • 2021-05-19
    • 2018-12-04
    • 2020-09-24
    • 1970-01-01
    • 2018-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多