【问题标题】:Need to execute set of commands on remote machine using shell script需要使用 shell 脚本在远程机器上执行一组命令
【发布时间】:2016-03-07 19:17:57
【问题描述】:

我正在尝试以下方法:

#!/bin/bash

NodeIP="10.63.12.19"
userpd="password"



expect -c "
    spawn ssh root@$NodeIP
    expect "*assword:"
    send \"$userpd\r\"
    interact
    " 

CONFIG_FILE="/etc/main/params.conf"

User_val=10
IP_val=5
Blocking_max=2
Monitoring_max=2

sed -c -i "s/\(userMaxFailAttempts *= *\).*/\1$User_max/" $CONFIG_FILE
sed -c -i "s/\(userMonitoringWindow *= *\).*/\1$Monitoring_window/" $CONFIG_FILE
sed -c -i "s/\(userBlockingWindow *= *\).*/\1$Blocking_window/" $CONFIG_FILE
sed -c -i "s/\(ipMaxFailAttempts *= *\).*/\1$IP_max/" $CONFIG_FILE
sed -c -i "s/\(ipMonitoringWindow *= *\).*/\1$Monitoring_window/" $CONFIG_FILE
sed -c -i "s/\(ipBlockingWindow *= *\).*/\1$Blocking_window/" $CONFIG_FILE 

我需要在远程服务器上执行 ssh 并编辑上面的 param.conf 文件,并且我还需要在该 ssh 会话中执行一些其他命令。目前,文件没有被上述方法修改

【问题讨论】:

  • 您需要在 Expect 会话中运行 sed 命令 - 就脚本而言,您在 Expect 会话结束后运行它们,因此您回到了本地机器上。

标签: bash shell ssh sed expect


【解决方案1】:

您应该设置 ssh 密钥身份验证,然后您根本不需要期望(并且您不会将密码硬编码在纯文本文件中)

#!/bin/bash

NodeIP="10.63.12.19"
CONFIG_FILE="/etc/main/params.conf"
User_val=10
IP_val=5
Blocking_max=2
Monitoring_max=2

ssh root@$NodeIP << end_commands
  sed -c -i "s/\\(userMaxFailAttempts *= *\\).*/\\1$User_max/"           "$CONFIG_FILE"
  sed -c -i "s/\\(userMonitoringWindow *= *\\).*/\\1$Monitoring_window/" "$CONFIG_FILE"
  sed -c -i "s/\\(userBlockingWindow *= *\\).*/\\1$Blocking_window/"     "$CONFIG_FILE"
  sed -c -i "s/\\(ipMaxFailAttempts *= *\\).*/\\1$IP_max/"               "$CONFIG_FILE"
  sed -c -i "s/\\(ipMonitoringWindow *= *\\).*/\\1$Monitoring_window/"   "$CONFIG_FILE"
  sed -c -i "s/\\(ipBlockingWindow *= *\\).*/\\1$Blocking_window/"       "$CONFIG_FILE"
end_commands

您需要将反斜杠加倍,因为 shell 在将命令发送到远程主机之前会进行一轮替换。

【讨论】:

  • 它在哪里接受密码?问题是这个脚本应该用有效的密码ssh然后执行特定的操作
  • 如果可能,不要使用expect登录。将密码存储在纯文本文件中(以及所有用户的 root 密码!)是可怕的。使用ssh-keygen 在本地机器上生成一个ssh 密钥,然后使用ssh-copy-id root@$NodeIP 将公钥传输到远程机器。
最近更新 更多