- 论坛徽章:
- 1
|
请教自动登陆ssh,然后ftp自动传文件的脚本
下面是我用來做兩次telnet的程序...你可以參考並修改..
要不可以去www.cpan.org去找Expect.pm的說明文件..
use Expect;
$NM_ID = "aaa";
$NM_PWD = "aaabbb";
$NE_ID = "ccc";
$NE_PWD = "dddeee";
$timeout = 30;
$exp = new Expect;
## 設定terminal type
#$exp->;stty(qw(-raw -echo));
## 重設定buffer 大小
#$exp->;match_max(1024);
## 重設定timeout時間(有收到東西就重設定)
$exp->;restart_timeout_upon_receive(1);
## 看詳細內容
#$exp->;exp_internal(1);
## 開啟Debug模式
#$exp->;debug(2);
#$exp->;send_slow(0);
## 顯示標準輸出
$exp->;log_stdout(0);
$exp->;spawn("telnet $NM_IP" || die "cannot spawn telnet: $!\n";
$error_value =0;
$spawn_ok =0;
$exp->;expect( $timeout,
[ qr'login: $',
sub {
$spawn_ok = 1;
my $fh = shift;
$fh->;send("$NM_ID\r" ;
$fh->;clear_accum();
exp_continue; } ],
[ qr'sword: $' ,
sub {
$spawn_ok = 2;
my $fh = shift;
$fh->;send("$NM_PWD\r" ;
$fh->;clear_accum();
exp_continue; } ],
[ qr'Login incorrect',\&nm_error],
[ eof =>; \&nm_error ],
[ timeout =>; \&nm_error ],
'-re', qr'\012\$ $',
sub {
my $fh = shift;
$fh->;send("telnet $DSLAM_IP\r" ;
}
);
$spawn_ok = 0;
$exp->;expect( $timeout,
[ qr'Invalid name.',\&ne_error],
[ qr'Invalid password.',\&ne_error],
[ qr'Login:\s+$',
sub {
$spawn_ok = 1;
my $fh = shift;
$fh->;send("$NE_ID\r" ;
$fh->;clear_accum();
exp_continue; } ],
[ qr'sword: $' ,
sub {
$spawn_ok = 2;
my $fh = shift;
$fh->;send("$NE_PWD\r" ;
$fh->;clear_accum();
exp_continue; } ],
[ eof =>;\&ne_error ],
[ timeout =>; \&ne_error ],
'-re', qr'\d+>; $',
sub {
my $fh = shift;
$fh->;send("login\r" ;
}
);
$exp->;expect( $timeout,
[ eof =>;\&run_error ],
[ timeout =>; \&run_error ],
'-re', qr'>; $',
);
}
===>;任何我想expect要我做的事情
sub run_error{
$exp->;log_file($LOG_FILE);
$exp->;log_file->;print("\r\n無法下指令##\r\n" ;
$error_value = 999;
}
sub nm_error {
$exp->;log_file($LOG_FILE);
if($spawn_ok == 1) {
$exp->;log_file->;print("\r\n帳號密碼錯誤\r\n" ;
}elsif($spawn_ok == 2) {
$exp->;log_file->;print("\r\n無法登錄\r\n" ;
}else{
$exp->;log_file->;print("\r\n#10# 無法連線\r\n");
}
$error_value = 10;
$exp->;log_file(undef);
# $exp->;hard_close;
die "10\n";
}
sub ne_error {
$exp->;log_file($LOG_FILE);
if($spawn_ok == 1) {
$exp->;log_file->;print("\r\n登錄失敗\r\n");
}elsif($spawn_ok == 2) {
$exp->;log_file->;print("\r\n無法登錄\r\n");
}else{
$exp->;log_file->;print("\r\n#12# 無法連線\r\n");
}
$error_value = 12;
$exp->;log_file(undef);
# $exp->;hard_close;
die "12\n";
} |
|