批量修改远程 Linux 服务器用户密码

首先是一个调用脚本,循环读取文本文件

文本文件格式为:ip loginuser loginpass passuser newpass

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
#!/bin/bash
if [ "$1" = "" ] || [ "$1" = "-h" ] || [ "$1" = "--help" ]
then
    echo "Usage: chpasswd.sh  path/iplist "
    exit
fi
cat $1 | while read line
do
    [ -z "$line" ] && continue
    expect ~/expect/chpasswd.expect $line;
done
echo -e "\n  well done\n"

以下是 expect 主程序

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#!/usr/bin/expect

#登录的用户名
set loginuser [lindex $argv 1]
#密码
set loginpass  [lindex $argv 2]

#要修改的用户名
set passuser [lindex $argv 3]
#要修改成的新密码
set newpass [lindex $argv 4]

set ipaddr [lindex $argv 0]
set timeout 300
set cmd_prompt "]#|~]?"

#---------------------------------------------------通过 ssh 登录
spawn ssh $loginuser@$ipaddr
set timeout 300
expect {
    -re "Are you sure you want to continue connecting (yes/no)?" {
        send "yes\r"
    } -re "assword:" {
        send "$loginpass\r"
    } -re "Permission denied, please try again." {
        exit
    } -re "Connection refused" {
        exit
    } -re $cmd_prompt {
        send "\r"
    } timeout {
        exit
    } eof {
        exit
    }
}

#-------------------------------------------修改密码
send "sudo passwd $passuser \r";
expect {
    "password for $loginuser:" {
        send "$loginpass\r"
    }
}

expect {
    "New password:" {
        send "$newpass\r"
    }
    "新的 密码:" {
        send "$newpass\r"
    }
    "passwd: Only root can specify a user name." {
        exit
    }
}

expect {
    "Retype new password:" {
        send "$newpass\r"
    }
    "重新输入新的 密码:" {
        send "$newpass\r"
    }
}

#---------------------------------------------退出
expect -re $cmd_prompt
exit
Licensed under CC BY-NC-SA 4.0
最后更新于 Sep 08, 2019 03:12 +0800
comments powered by Disqus
墩墩家的幸福生活
Built with Hugo
主题 StackJimmy 设计