#!/usr/bin/perl =pod Name:autossh1.0 author:扶凯(fukai) web site:www.php-oa.com 密码文件存放位置请自行设置 Last Modify:2009-04-12 修复进入远程主机后vi之类的程序的window的大小有问题 Last Modify:2009-05-23 修复第一次ssh时出现yes不能正常回应的问题,新功能加载命令list的功能 =cut use strict; use Expect; use Getopt::Std; use vars qw($opt_h $opt_s $opt_l $opt_c $opt_f); getopts('h:s:lc:f:'); if($opt_h){ last unless -e $opt_h; my @argument; open PASSFILE,"<$opt_h" or die "$!"; while() { next if (/^#/); @argument = split; if( $#argument+1 == 4 or $#argument+1 == 3) { &connect("\@argument"); } elsif($#argument+1 == 6 or $#argument+1 == 7) { &connect("\@argument"); } } }elsif($opt_l){ open PASSFILE," ) { if (/^#/){ print ; } else { @argument = split; if( $#argument+1 == 4 or $#argument+1 == 3) { print "@argument[0] ### @argument[3] \n"; } elsif($#argument+1 == 6 or $#argument+1 == 7) { print "@argument[3] ### @argument[6] \n"; } else { print join @argument ; print "\n"; } } } exit; } elsif($opt_s) { my $regex = $opt_s; my @argument; open PASSFILE,") { next if (/^#/); @argument = split; if( $#argument+1 == 4 or $#argument+1 == 3) { if(@argument[3] =~ /$regex/ or @argument[0] =~ /$regex/ ) { &connect("\@argument"); } } elsif($#argument+1 == 6 or $#argument+1 == 7) { if(@argument[6] =~ /$regex/ or @argument[3] =~ /$regex/ ) { &connect("\@argument"); } } } } elsif($opt_c) { } else { print < [more options] Available options -s : serch host name -h : host list -l : Display this host list -c : Command -f : Command list END exit; } sub connect(){ my $exp = new Expect; my @argument = split; my ($host,$user,$passwd,$host1,$root1,$passwd1,$pass,$error); if($#argument<=4) { ($host,$user,$passwd) = @argument; } else { ($host,$user,$passwd,$host1,$root1,$passwd1) = @argument; } my $command = "ssh -l $user $host -X"; $exp->spawn($command) or die "Cannot spawn $command: $!\n"; $exp->send("yes\r\n") if $exp->expect(3,'connecting (yes/no)?'); #$exp->send("yes\r\n") if ($pass); $exp->send("$passwd\n") if $exp->expect(3, 'password'); $exp->expect(30, '#'); #--如果需要转发ssh---- if($#argument>4){ $exp->send("ssh -l $root1 $host1 \n"); $exp->send("$passwd1\n") if $exp->expect(30, 'password'); $exp->expect(30, '#'); } #----------- if($opt_c){ $exp->send("$opt_c\r\n") if $exp->expect(1, '#');; #$exp->soft_close(); $exp->hard_close() if $exp->expect(3,'#'); } elsif($opt_f) { last unless (-e $opt_f); #如果有这个命令,并这个路径存在,才运行,不然退出. open COMMFILE,"<$opt_f"; while(){ $exp->send("$_\r\n"); sleep 1; } } else { $exp->slave->clone_winsize_from(\*STDIN); $SIG{WINCH} = \&winch; sub winch { $exp->slave->clone_winsize_from(\*STDIN); kill WINCH => $exp->pid if $exp->pid; $SIG{WINCH} = \&winch; } $exp->interact() if $exp->expect(2, '#'); } $exp->hard_close() if $exp->expect(2, '#'); print "登录受限\n" if $exp->expect(3,'Permission denied'); print "\n主机不可访问\n" if $exp->expect(3,'Connection refused'); }