#!/usr/bin/perl
use strict;
use warnings;
use Net::SSH::Expect;
my @ssh_list;
my @array_list=(0..9,'a'..'z');# 生成隨機種子
my $new_user_pass;
while (<>) {
$new_user_pass=join '', map{$array_list[int rand @array_list]}0..7;#生成隨機密碼 0..7表示8位密碼
@ssh_list=split/\s+/,$_;
print $ssh_list[0]."正在修改密碼\n";
&ssh_test( "$ssh_list[0]", "$ssh_list[1]", "$ssh_list[2]", "$ssh_list[3]" );
}
sub ssh_test() {
my ( $host, $port, $user, $pass ) = @_;
my $ssh = Net::SSH::Expect->new(
host => $host,
port => $port,
password => $pass,
user => $user,
no_terminal => 0,
raw_pty => 1,
timeout => 6,
);
open FI, ">> /home/mcshell/newuser.txt" or die $!;##新密碼所放的位置
print FI "-" x 80, "\n";
$ssh->debug(0);
$ssh->run_ssh() or die "SSH process couldn't start: $!";
$ssh->waitfor( '\(yes\/no\)\?$', 2 ); #交互式修改密碼,給予2秒的時間
$ssh->send("yes\n");
$ssh->waitfor( 'password:\s*$/', 2);
$ssh->send("$ssh_list[3]");
$ssh->send("su - root"); # 其實這裏我原本的用戶不是root,爲了更好的擴展
$ssh->waitfor( 'Password:\s*$', 2 );# 常常服務器不允許root直接登陸的,因此要用其餘
$ssh->send("$ssh_list[3]"); #用戶來切換root
$ssh->waitfor( '#\s*', 2 );
$ssh->send("passwd $ssh_list[2]");
$ssh->waitfor( 'password:\s*$', 2 );
$ssh->send("$new_user_pass");
$ssh->waitfor( 'password:\s*$', 2 );
$ssh->send("$new_user_pass");
$ssh->waitfor( '#\s*', 2 );
print FI "$host\t$port\t$user\t$new_user_pass\n";
$ssh->close();
close FI;
print "修改完成\n";
print "-" x 30, "\n";
}