2013-10-07 59 views
2

我试图使用expect在Perl脚本中使用系统调用以递归方式在远程服务器上创建目录。相关电话如下:在系统中使用Perl期望()

system("expect -c 'spawn ssh $username\@$ip; expect '*?assword:*' {send \"$password\r\"}; expect '*?*' {send \"mkdir -p ~/$remote_start_folder/$remote_folder_name/$remote_username/$remote_date/\r\"}; expect '*?*' {send \"exit\r\"}; interact;'"); 

这工作正常。但是,如果这是第一次使用ssh访问远程机器,它会要求确认(yes/no)。我不知道在上面的声明中增加了哪些内容。有没有办法将它合并到上面的语句中(使用某种or -ing)?

回答

3

添加yes/no匹配的expect同一调用作为密码匹配:

expect '*yes/no*' {send "yes\r"; exp_continue;} '*?assword:*' {send \"$password\r\"}; 

这将寻找两场比赛,如果yes/no遇到exp_continue告诉Expect继续寻找密码提示。

完整的示例:

system(qq{expect -c 'spawn ssh $username\@$ip; expect '*yes/no*' {send "yes\r"; exp_continue;} '*?assword:*' {send "$password\r"}; expect '*?*' {send "mkdir -p ~/$remote_start_folder/$remote_folder_name/$remote_username/$remote_date/\r"}; expect '*?*' {send "exit\r"}; interact;'}); 

我也用qq,以避免逃避所有的报价。从-d标志示出shell中运行此命令指望在寻找能匹配:

Password: 
expect: does "...\r\n\r\nPassword: " (spawn_id exp4) match glob pattern 
    "*yes/no*"? no 
    "*?assword:*"? yes 

随着yes/no提示:

expect: does "...continue connecting (yes/no)? " (spawn_id exp4) match glob pattern 
    "*yes/no*"? yes 
... 
send: sending "yes\r" to { exp4 } 
expect: continuing expect 
... 
expect: does "...\r\nPassword: " (spawn_id exp4) match glob pattern 
    "*yes/no*"? no 
    "*?assword:*"? yes 
... 
send: sending "password\r" to { exp4 } 
1

你是你的生命不必要地复杂。

如果您想要Perl的类似于期望的功能,只需使用Expect模块。

如果要通过SSH与某个远程服务器交互,请使用CPAN提供的一些SSH模块:Net::OpenSSH,Net::SSH2,Net::SSH::Any

如果您不想确认远程主机密钥,请将选项StrictHostKeyChecking=no更改为ssh

例如:

use Net::OpenSSH; 

my $ssh = Net::OpenSSH->new($ip, user => $username, password => $password, 
          master_opts => [-o => 'StrictHostKeyChecking=no']); 

my $path = "~/$remote_start_folder/$remote_folder_name/$remote_username/$remote_date"; 
$ssh->system('mkdir -p $path') 
    or die "remote command failed: " . $ssh->error;