#!/usr/bin/expect -f # 从文件中读取远程服务器列表 set file [open "remote_hosts.txt" r] set remote_hosts [split [read $file] "\n"] close $file # 生成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 { 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" # 拷贝公钥到远程服务器 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"这一段代码有什么问题
时间: 2024-04-23 22:28:03 浏览: 14
这段代码看起来没有明显的错误。但是,有一点需要注意的是,你在远程服务器列表中使用了花括号 `{}`,这将导致整个列表被视为一个字符串。为了正确解析每个服务器的信息,你可以使用方括号 `[]` 来表示列表。
以下是修改后的代码示例:
```bash
#!/usr/bin/expect -f
# 从文件中读取远程服务器列表
set file [open "remote_hosts.txt" r]
set remote_hosts [split [read $file] "\n"]
close $file
# 生成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 {
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"
# 拷贝公钥到远程服务器
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.txt"文件中按照正确的格式(每个服务器一行,IP地址、用户名和密码之间用空格分隔)保存远程服务器的信息。这样,脚本就可以从文件中读取并使用这些信息进行配置。如果还有其他问题,请提供更多的详细信息。