【问题标题】:Solaris 11 Expect script test for ssh-key already installed? WITHOUT ssh-copy-id ssh-passSolaris 11 是否已经安装了 ssh-key 的脚本测试?没有 ssh-copy-id ssh-pass
【发布时间】:2021-04-07 01:55:32
【问题描述】:

我在 Solaris 11.4 服务器上有以下期望脚本。因为 Solaris 11 不附带 ssh-copy-id 或 ssh-pass。我想创建一个脚本来自动将我的 ssh 密钥复制到 100 多台服务器。经过一点谷歌期望似乎是唯一的选择 - 除非有人知道更好?

我可以让脚本将密钥复制到目标服务器上,但我需要的是如果密钥已安装,则脚本不要复制。

我可以检查的唯一方法是 ssh 登录是否直接进行而不要求输入密码。我的问题是如何测试空提示? .

如果未安装密钥,我会收到密码提示 - 然后我可以使用 expect 来完成密码并复制密钥。我已经尝试过测试“”(空),但这似乎与所有内容相匹配。任何建议都非常感谢。

#!/usr/bin/expect

set timeout 1200
set user [lindex $argv 0]
set host [lindex $argv 1]
set pass [lindex $argv 2]

set sshkeyfile  [open  ~/.ssh/id_rsa.pub r]
set sshid [read $sshkeyfile]
close $sshkeyfile

spawn ssh $user@$host "mkdir -m 700 ~/.ssh ; echo \" $sshid\" >> ~/.ssh/authorized_keys; chmod 600 ~/.ssh/authorized_keys"

expect {
"continue" { send "Yes\n" ; exp_continue }
"Password" { send "$pass\r"; interact}
"" { send "exit\n" ; exit 0 } # Exit if not asked for "continue/Password"
}

【问题讨论】:

  • 成功登录后,你的shell提示符是什么样的?

标签: shell ssh solaris expect


【解决方案1】:

这个怎么样:没有命令的ssh;如果看到密码,则设置一个布尔变量;当您点击 shell 提示时,如果变量为真,则附加到 authorized_keys

#!/usr/bin/expect

set timeout 1200
lassign $argv  user host pass

set sshkeyfile  [open  ~/.ssh/id_rsa.pub r]
set sshid [read -nonewline $sshkeyfile]
close $sshkeyfile

set sentPassword false
set prompt {\$ $}        ;# shell prompt ends with "dollar space"

spawn ssh $user@$host

expect {
    "continue" {
        send "Yes\r" 
        exp_continue
    }
    "Password" {
        set sentPassword true
        send "$pass\r"
        exp_continue
    }
    -re $prompt
}
if {$sentPassword} {
    send "mkdir -p -m 700 ~/.ssh ; echo \"$sshid\" >> ~/.ssh/authorized_keys; chmod 600 ~/.ssh/authorized_keys\r"
    expect -re $prompt
}
send "exit\r"
expect eof

其他变化:

  • lassign 在一个命令中处理命令行参数
  • read -nonewline 省略公钥中的尾随换行符
  • mkdir -p 以防止在目录已存在时出现错误消息。

【讨论】:

  • 天才:像魅力一样工作。
猜你喜欢
  • 2015-11-15
  • 2014-10-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-11
  • 1970-01-01
  • 1970-01-01
  • 2017-01-09
相关资源
最近更新 更多