Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2115607
  • 博文数量: 227
  • 博客积分: 10521
  • 博客等级: 上将
  • 技术积分: 3452
  • 用 户 组: 普通用户
  • 注册时间: 2006-10-20 14:59
个人简介

低调做人,高调做事!

文章分类

全部博文(227)

文章存档

2013年(4)

2012年(8)

2011年(16)

2010年(24)

2009年(92)

2008年(83)

分类: LINUX

2009-05-08 22:11:23

    因为管理的服务器相对比较多,每次输入密码都比较麻烦,所以一直想实现自动登录的功能,今天发现一篇文章作者是用perl写的,自己在本地做了个实验,发现有一些问题,于是就修改下,以适合自己的应用环境,修改如下:

1,远程服务器不允许root远程登录,ssh端口不是默认22端口。
2,在匹配 (yes\/no\) 的时候做了修改。

原文链接如下:


使用方法如下,

1,有一个配置文件表,如下:
[root@test opt]# more pwd.txt
#remote host     port    user        passwd        s_user    s_passwd         note
192.168.20.1     999     test       
123           root      654              node1

2,使用方法如下:
#显示所有的主机列表
[root@mail opt]# ./auto_ssh.pl -l
#remote host     port    user        passwd        s_user    s_passwd         note
192.168.20.1     999     test       
123           root      654              node1

#-s参数会查找你的列表中所有主机和备注,只要找到就会自动连接
[root@mail opt]# ./auto_ssh.pl -s  node1



脚本如下:

#!/usr/bin/perl -w

use strict;
use Expect;
use Getopt::Std;

use vars qw($opt_l $opt_s);
getopts('ls:');

my $passwd_file = '/opt/pwd.txt';

if ($opt_l) {
    open PASSFILE, "< $passwd_file";
    my @argument;
    while () {
        if (/^#/) {
            print;
        }
        else {
            @argument = split;
            if ( $#argument + 1 == 7 ) {
                print "$argument[0] ### $argument[6] \n";
            }
            else {
                print join @argument;
                print "\n";
            }
        }
    }
    exit;
}
elsif ($opt_s) {
    my $regex = $opt_s;
    my @argument;
    open PASSFILE, "< $passwd_file" or die "$!";
    while () {
        next if (/^#/);
        @argument = split;
        if ( $#argument + 1 == 7 ) {
            if ( $argument[6] =~ /$regex/ ) {
                &connect("\@argument");
            }
        }
    }

}

else {
    print <Usage: ccssh [options]
  Available options
    -s : serch host name
    -l : Display this host list
END
    exit;
}

#----------------------------------------------------------------------
sub connect() {

    my @argument = split;
    my ( $host, $port, $user, $passwd, $s_user, $s_passwd );
    ( $host, $port, $user, $passwd, $s_user, $s_passwd ) = @argument;

    my $exp     = new Expect;
    my $command = "ssh -l $user $host -p $port";
    $exp->spawn($command) or die "Cannot spawn $command: $!\n";

    my $pass = $exp->expect( 6, 'connecting' );
    $exp->send("yes\r\n") if ($pass);
    $pass = $exp->expect( 6, 'password' );
    $exp->send("$passwd\r\n");
    $pass = $exp->expect( 6, '$' );
    $exp->send("su -\r\n");
    $pass = $exp->expect( 6, 'password' );
    $exp->send("$s_passwd\r\n");

    $exp->interact();

}

阅读(6693) | 评论(0) | 转发(1) |
给主人留下些什么吧!~~