如何使用bash /期望检查一个SSH登录作品 [英] How to use bash/expect to check if an SSH login works

查看:132
本文介绍了如何使用bash /期望检查一个SSH登录作品的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的团队管理多台服务器和公司政策规定,这些服务器上的密码必须改变,每两三个星期。有时候,我们的密码官方数据库变得过时无论出于何种原因的(人忘记更新它,通常情况下),但我们有时不能确定这一点,直到几个月后,因为我们不坚持使用每个服务器。

My team manages many servers, and company policy dictates that the passwords on these servers must be changed every couple of weeks. Sometimes, our official database of passwords gets out of date for whatever reason (people forget to update it, usually), but we cannot identify this sometimes until months later, since we don't consistently use every server.

我想编写一个脚本,将刮从数据库中的密码,并使用这些密码,每天晚上来尝试(SSH)登录到每个服务器,并与结果球队发送电子邮件。我能刮登录信息数据库,但我不知道如何检查ssh登录是否成功并不指望

I want to write a script that will scrape the passwords from the database, and use those passwords to attempt an (ssh) login to each server every night, and send an email with the results to the team. I am able to scrape the database for login information, but I'm not sure how to check whether ssh login was successful or not in expect.

我无法完成这个任务使用公共密钥认证即可。我的希望的密码验证,所以我可以验证密码。

I cannot use public key authentication for this task. I want password authentication so I can verify the passwords.

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

I disable public-key authentication by specifying the following file:

PasswordAuthentication=yes
PubkeyAuthentication=no

我尝试在expect脚本:

My attempts at the expect script:

# $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\'"

我想,也许退出状态可能表明成功?找不到在手册页,虽然任何事情。

I thought maybe exit status could indicate the success? Couldn't find anything in the man pages though.

推荐答案

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

I've been using something like the script below for a similar task.

#!/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 /期望检查一个SSH登录作品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆