PerlでSSHへ接続したくなったのでNet::SSH2を使ってみた
Net::SSH2を使うにはlibssh2-develを使用するらしいのでインストール
# yum -y install libssh2-devel
cpanを使ってNet::SSH2をインストール
# cpan -i Net::SSH2
# cpan -i Net::OpenSSH::Compat::SSH2
実装例
SSHでサーバにログインしてpublic_htmlに移動し、lsコマンドを実行する
#!/usr/bin/perl
use strict;
use warnings;
# SSHのバナーを表示したい場合
#use Net::OpenSSH::Compat::SSH2 qw(:supplant);
use Net::SSH2;
# バッファーサイズ
use constant BUFLEN => 512;
my $host = ""; # 接続先ホスト
my $user = ""; # ユーザ名
my $pass = ""; # パスワード
my ($len, $buf);
my $ssh2 = Net::SSH2->new();
$ssh2->connect($host) or die "$!";
if( $ssh2->auth_password($user,$pass)) {
my $chan = $ssh2->channel();
$chan->blocking(0);
$chan->shell();
$chan->write("cd public_html\n");
select(undef,undef,undef,0.2);
print $buf while ($len = $chan->read($buf, BUFLEN));
$chan->write("ls -al ./\n");
select(undef,undef,undef,0.2);
print $buf while ($len = $chan->read($buf, BUFLEN));
$chan->close();
}
これは色々使えそうですね
参考サイト
Perl Tips | Perl で、ssh でリモートのサーバにアクセスしてファイルをアップロード(SCP)する方法 (Net::SSH2)
自分イノベーション – 気まぐれ勉強メモ Net::SSH2を使ってみた
Net::SSH2と公開鍵
A little demo for Net::SSH2
0 Comments.