bash - 如何使用 bash/expect 检查 SSH 登录是否有效

标签 bash shell ssh expect

我的团队管理着许多服务器,公司政策规定这些服务器上的密码必须每两周更改一次。有时,我们的官方密码数据库会因为某种原因而过时(人们通常会忘记更新它),但我们有时要到几个月后才能识别这一点,因为我们不会始终如一地使用每台服务器。

我想编写一个脚本,从数据库中抓取密码,并使用这些密码每晚尝试 (ssh) 登录到每台服务器,并将包含结果的电子邮件发送给团队。我能够从数据库中抓取登录信息,但我不确定如何按预期检查 ssh 登录是否成功

我无法为此任务使用公钥身份验证。我想要密码身份验证,这样我就可以验证密码。

我通过指定以下文件禁用公钥身份验证:

PasswordAuthentication=yes
PubkeyAuthentication=no

我对 expect 脚本的尝试:

# $1 = host, $2 = user, $3 = password, $4 = config file
expect -c "spawn ssh $2@$1 -F $4
expect -re \".*?assword.*?\"
send \"$3\n\"
...
send \'^D\'"

我想也许退出状态可以指示成功?但是在手册页中找不到任何内容。

最佳答案

我一直在使用类似于下面的脚本来完成类似的任务。

#!/bin/sh
# Run using expect from path \
exec expect -f "$0" "$@"
# Above line is only executed by sh
set i 0; foreach n $argv {set [incr i] $n}
set pid [ spawn -noecho ssh $1@$3 $4 ]
set timeout 30
expect {
    "(yes/no)" {
        sleep 1
        send "yes\n"
        exp_continue
    }
    "(y/n)" {
        sleep 1
        send "y\n"
        exp_continue
    }
    password {
        sleep 1
        send "$2\n"
        exp_continue
    }
    Password {
        sleep 1
        send "$2\n"
        exp_continue
    }
    "Last login" {
        interact
    }
    "Permission denied" {
        puts "Access not granted, aborting..."
        exit 1
    }
    timeout {
        puts "Timeout expired, aborting..."
        exit 1
    }
    eof {
        #puts "EOF reached."
    }
}
set status [split [wait $pid]]
set osStatus [lindex $status 2]
set procStatus [lindex $status 3]
if { $osStatus == 0 } {
    exit $procStatus
} else {
    exit $procStatus
}

关于bash - 如何使用 bash/expect 检查 SSH 登录是否有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12282251/

相关文章:

bash - 有没有办法避免 bash 中的位置参数?

macos - ZSH 中的 %~(百分号)是什么?

linux - ksh:评估从文件中读取的一行

php - 使用 PHP SSH 连接到远程服务器

linux - Linux Bash 中的模式匹配

linux - 创建文件所需的 awk sed 帮助

linux - 重写一个脚本,让它接受选项参数来控制它的行为

linux - Makefile 和 Shell 脚本 (Bash)

ssh - 如何为集群创建自动 "ssh"

ssh - 无法使用URI形式ssh