SSH Unixサーバーでシェルコマンドを実行するためのJava JSchの例

今日はJSchの例のチュートリアルを見てみましょう。JSchを使用してJavaでSSH接続を作成することができます。以前、SSHサーバー上のリモートデータベースに接続するプログラムを書きましたが、今日はSSH対応のサーバーに接続し、シェルコマンドを実行するためのプログラムをご紹介します。JavaプログラムからリモートSSHサーバーに接続するためにJSchを使用しています。

JSchの例を日本語で言い換えると、次のようになります。

JSchの使用例

公式ウェブサイトからJSchのjarファイルをダウンロードすることができます。また、以下のMaven依存関係を使用してもJSchのjarファイルを取得することができます。

<dependency>
    <groupId>com.jcraft</groupId>
    <artifactId>jsch</artifactId>
    <version>0.1.53</version>
</dependency>

以下は、サーバー上で「ls -ltr」というコマンドを実行するためのシンプルなJSchの例です。

import java.io.InputStream;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;


public class JSchExampleSSHConnection {

	/**
	 * JSch Example Tutorial
	 * Java SSH Connection Program
	 */
	public static void main(String[] args) {
	    String host="ssh.scdev.com";
	    String user="sshuser";
	    String password="sshpwd";
	    String command1="ls -ltr";
	    try{
	    	
	    	java.util.Properties config = new java.util.Properties(); 
	    	config.put("StrictHostKeyChecking", "no");
	    	JSch jsch = new JSch();
	    	Session session=jsch.getSession(user, host, 22);
	    	session.setPassword(password);
	    	session.setConfig(config);
	    	session.connect();
	    	System.out.println("Connected");
	    	
	    	Channel channel=session.openChannel("exec");
	        ((ChannelExec)channel).setCommand(command1);
	        channel.setInputStream(null);
	        ((ChannelExec)channel).setErrStream(System.err);
	        
	        InputStream in=channel.getInputStream();
	        channel.connect();
	        byte[] tmp=new byte[1024];
	        while(true){
	          while(in.available()>0){
	            int i=in.read(tmp, 0, 1024);
	            if(i<0)break;
	            System.out.print(new String(tmp, 0, i));
	          }
	          if(channel.isClosed()){
	            System.out.println("exit-status: "+channel.getExitStatus());
	            break;
	          }
	          try{Thread.sleep(1000);}catch(Exception ee){}
	        }
	        channel.disconnect();
	        session.disconnect();
	        System.out.println("DONE");
	    }catch(Exception e){
	    	e.printStackTrace();
	    }

	}

}

もしJSchの例題プログラムの実行に問題があれば、教えてください。この例題プログラムは、JavaプログラムでSSH接続を作成するための非常にシンプルな例です。JSchのjarファイルは公式ウェブサイトからダウンロードできますので、そちらをご利用ください。

コメントを残す 0

Your email address will not be published. Required fields are marked *