#!/usr/bin/expect -f set remote_hosts { {"172.17.120.186" "root" "Haiyisec@123"} {"172.17.120.76" "root" "Haiyisec@123"} } # 生成SSH密钥对 send_user "在服务器上生成SSH密钥对 ...\n" spawn ssh-keygen -t rsa expect { "Enter file in which to save the key*" { send -- "\r" exp_continue } "Enter passphrase*" { send -- "\r" exp_continue } "Enter same passphrase again:" { send -- "\r" } } expect eof # 遍历远程服务器列表 foreach server $remote_hosts { send_user "配置服务器 $remote_host ...\n" # 拷贝公钥到远程服务器 spawn ssh-copy-id $remote_user@$remote_host expect { "*yes/no*" { send -- "yes\r" exp_continue } "*assword:" { send -- "$remote_password\r" } } expect eof send_user "服务器 $remote_host 配置完成!\n\n" } send_user "所有服务器SSH免密登录配置完成!\n"将remote_hosts写在文本里
时间: 2023-08-20 22:06:21 浏览: 42
抱歉,但我无法执行你所描述的操作。我是一个基于文本的AI模型,无法直接读取或写入文本文件。我只能处理和生成文本内容。
你可以将远程服务器列表保存在一个文本文件中,然后在脚本中读取该文件并解析出远程服务器的信息。以下是一个示例:
```bash
#!/usr/bin/expect -f
# 从文件中读取远程服务器列表
set file [open "remote_hosts.txt" r]
set remote_hosts [split [read $file] "\n"]
close $file
# 遍历远程服务器列表
foreach server $remote_hosts {
set parts [split $server " "]
set remote_host [lindex $parts 0]
set remote_user [lindex $parts 1]
set remote_password [lindex $parts 2]
send_user "配置服务器 $remote_host ...\n"
# 后续代码...
}
```
在这个示例中,我们使用`open`命令打开名为"remote_hosts.txt"的文本文件,并将其保存在`file`变量中。然后,我们使用`read`命令读取文件内容,并使用换行符"\n"对其进行分割,得到一个远程服务器列表。接下来,我们使用`foreach`循环遍历这个列表,并使用`split`命令将每个服务器条目分割成IP地址、用户名和密码。最后,我们将这些信息分别赋值给`remote_host`、`remote_user`和`remote_password`变量,并执行后续的代码。
请确保在"remote_hosts.txt"文件中按照正确的格式(每个服务器一行,IP地址、用户名和密码之间用空格分隔)保存远程服务器的信息。这样,脚本就可以从文件中读取并使用这些信息进行配置。