Perl腳本學習經驗(四)--Perl中sftp的使用


使用sftp,需要使用Except模塊,該模塊需要下載安裝在perl目錄下,可以上http://www.cpan.org/上下載對應的安裝包;
1. 用root用戶登錄環境;
2. cd /usr/lib/perl5/
3. 上傳包IO-Tty-1.10.tar.gz 和 Expect-1.21.tar.gz到perl5目錄下;
4. 安裝IO-Tty-1.10
 tar -zxvf IO-Tty-1.10.tar.gz
 cd IO-Tty-1.10/
 perl Makefile.PL
 make
 make test
 make install
5. 安裝Expect-1.21
 tar -zxvf Expect-1.21.tar.gz
 cd Expect-1.21/
 perl Makefile.PL
 make
 make test
 make install

使用use Expect;
Demo:
    my $ssh = Expect->new;
    my $timeout = 10;
    $ssh->raw_pty => 1;
    $ssh->spawn("sftp $User\@$Server") or die "spawn failed!\n";
    $ssh->expect($timeout,[qr/continue connecting (yes\/no)?/,sub{$ssh->send("yes\n");exp_continue;}],
                          [qr/Password:/,sub{$ssh->send("$Password\n");exp_continue;}],
                          [qr/sftp>/,sub{$ssh->send("cd config\n");}]);
                         
    $ssh->expect($timeout,[qr/sftp>/,sub{$ssh->send("put $g_local_file $g_file\n");}]);
    $ssh->expect(86400,"sftp>") or die "not see sftp tip for exit!";
    $ssh->send("exit\n");
    $ssh->soft_close();

 

備注:

 1. 第一次使用sftp的時候,沒有記錄對應ip,所以會有以下提示:

Connecting to 192.168.1.1...
The authenticity of host 192.168.1.1(192.168.1.1)' can't be established.
RSA key fingerprint is 86:39:3b:c9:4b:90:df:e9:39:1d:3c:fb:56:26:2f:28.
Are you sure you want to continue connecting (yes/no)?

所以在腳本中需要發送yes

 

  2.exp_continue 匹配到就執行send中的命令,匹配不到就繼續執行下面的命令;

     如果不加exp_continue,順序執行腳本命令;


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM