【问题标题】:Expect script for checking ssh connection for a list of ips用于检查 ssh 连接以获取 ips 列表的预期脚本
【发布时间】:2015-08-28 10:54:29
【问题描述】:

谁能帮我创建一个期望脚本来在服务器列表上执行 SSH 并检查它是否正常。我不需要交互,不需要在每个服务器上触发任何命令,我只想做一个 ssh 并出来,返回代码说明它是否成功。

Expect 在这里很重要,因为我没有设置无密码连接的选项。也有可能在其中一些服务器上设置了无密码连接。

我尝试了类似的方法:

#!/usr/local/bin/expect
set timeout 10
set ip [lindex $argv 0]
set user [lindex $argv 1]
set password [lindex $argv 2]
set prompt "(>|%|\\\\\\\$|#|]|) \$"
spawn ssh "$user\@$ip"
expect "Password:"
send "$password\r"
send "echo hello\r"
expect "hello"
send "exit\r"

但这会卡在第一台服务器上,之后什么都不做。

谢谢, 皮尤什

【问题讨论】:

    标签: shell ssh scripting expect


    【解决方案1】:

    一般的想法可以是生成 ssh 并关闭连接的过程,该过程将保持范围本地的连接,因此全局 spawn_id 根本不会受到影响。

    #!/usr/bin/expect
    proc isHostAlive {host user pwd} {
     # We escaped the `$` symbol with backslash to match literal '$'
     # Commonly used prompt types
     set prompt "#|%|>|\\\$"
     set timeout 60
     spawn ssh $user@$host
     expect {
        timeout  {return FAIL}
        "(yes/no)" {send "yes\r";exp_continue}
        "password:" {send "$pwd\r";exp_continue}
        -re $prompt 
     }
     set msg "Hello World"
     send "echo $msg\r"
     expect { 
        timeout {return FAIL}
        "\r\n$msg"
     }
     send "exit\r"
     expect {
        timeout {return FAIL}
        eof
     }
     return PASS
    }
    
    # Lists to maintain the each host's information 
    set serverList {server1 server2 server3}
    set userList {user1 user2 user3}
    set pwdList {pwd1 pwd2 pwd3}
    
    # Looping through all the servers and checking it's availability
    foreach server $serverList user $userList pwd $pwdList { 
        puts "\n==>Status of $server : [isHostAlive $server $user $pwd]\n"
    }
    

    使用exp_continue,即使任何主机没有密码,我们也可以处理。基本上exp_continue 将导致expect 再次运行。因此,在提到的短语中,无论哪个来,都会被处理。即如果expect看到(yes/no),它将发送yes,如果expect看到password,它将发送密码值等等。然后expect会再次继续等待整组词组。

    我之所以添加yes/no是因为假设需要保存主机的RSA指纹。

    成功登录后,我正在回显Hello World 并期待回显消息。如果你注意到了,我在期望语句中使用了\r\n$msg。为什么我们在这里需要\r\n?

    这就是原因。每当我们发送期望也会看到的命令时,它也会尝试与之匹配。如果匹配,它将照此进行。

    回显命令输出示例

    dinesh@dinesh-VirtualBox:~/stackoverflow$ echo Hello World
    Hello World
    dinesh@dinesh-VirtualBox:~/stackoverflow$ 
    

    我们想要的字符串已经在send 命令中可用。因此,为了确保匹配的期望字符串仅来自实际的回显响应,我添加了\r\n,这将帮助我们匹配必要的内容。

    然后在proc 的最后,我发送exit 命令,它将关闭ssh 连接并匹配相同的eof(文件结尾)。在各种失败情况下,该过程将返回FAIL。

    【讨论】:

    • 谢谢,这正是我需要的:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-27
    • 1970-01-01
    • 2015-11-18
    • 1970-01-01
    • 2010-12-22
    • 1970-01-01
    • 2021-05-31
    相关资源
    最近更新 更多