Dan*_*ats 9 ssh bash shell expect
我的团队管理着许多服务器,公司政策规定必须每隔几周更改这些服务器上的密码.有时候,我们的官方密码数据库因任何原因都会过时(人们通常会忘记更新它),但我们有时会在几个月之后才发现这一点,因为我们并不总是使用每台服务器.
我想编写一个脚本来清除数据库中的密码,并使用这些密码每晚尝试(ssh)登录到每个服务器,并将结果发送给团队.我能够抓取数据库的登录信息,但我不知道如何检查ssh登录是否成功.
我不能使用公钥认证来完成此任务.我想要密码验证,所以我可以验证密码.
我通过指定以下文件禁用公钥验证:
PasswordAuthentication=yes
PubkeyAuthentication=no
Run Code Online (Sandbox Code Playgroud)
我对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\'"
Run Code Online (Sandbox Code Playgroud)
我想也许退出状态可能表明成功了吗?但是在手册页中找不到任何东西.
我一直在使用类似下面的脚本来执行类似的任务.
#!/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
}
Run Code Online (Sandbox Code Playgroud)