在日常的系统管理中,当服务器很多的时候,我们一般需要批量修改服务器的密码,或者执行某一个系统命令,这个时候,如果一台一台服务器去登陆,显得效率不高,如果可以批量进行执行,那是很爽的事情,下面这段代码就可以实现这样的功能,并且写入日志文件,一台服务器写入一个日志文件,iplist文件的格式是没一台服务器的ip地址是一行,代码如下:
#!/usr/bin/perl
use strict;
use warnings;
use Net::SSH::Expect;
my $user = 'aaa';
my $pass = '123456';
my $root_pass = 'abcdef';
my $new_user_pass = '654321';
my $port = '22';
my $file = '/home/aaa/iplist';
open FILE, "< $file" or die "can't open file $file ($!)";
while () {
next if $_ =~ /^#/;
print $_;
&ssh_host( "$_", "$port", "$user", "$pass" );
}
sub ssh_host() {
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 FH, ">> /home/aaa/log_$host" or die $!;
print FH "-" x 80, "\n";
my $start_time = localtime;
print FH "start \tat $start_time\n";
$ssh->debug(0);
$ssh->run_ssh() or die "SSH process couldn't start: $!";
$ssh->waitfor( '\(yes\/no\)\?$', 6 );
$ssh->send("yes\n");
$ssh->waitfor( 'password:\s*$/', 6 );
$ssh->send("$pass");
$ssh->send("su - root");
$ssh->waitfor( 'Password:\s*$', 6 );
$ssh->send("$root_pass");
$ssh->waitfor( '#\s*', 6 );
print FH "root login ok. \n";
$ssh->send("passwd $user");
$ssh->waitfor( 'password:\s*$', 6 );
$ssh->send("$new_user_pass");
$ssh->waitfor( 'password:\s*$', 6 );
$ssh->send("$new_user_pass");
$ssh->waitfor( '#\s*', 6 );
my $ls = $ssh->exec("id");
print FH "$ls\n";
print FH "chang password ok!!!!!!!\n";
my $end_time = localtime;
print FH "end \tat $end_time\n";
$ssh->close();
close FH;
print "-" x 30, "\n";
}
perl下批量修改远程服务器密码
最新推荐文章于 2024-08-16 21:49:01 发布