JAVA開発メモ
のバックアップ(No.1)
 

[トップ|一覧|単語検索|最終更新|バックアップ|ヘルプ]


import java.io.IOException; import org.apache.commons.io.IOUtils; import ch.ethz.ssh2.Connection; import ch.ethz.ssh2.Session; import ch.ethz.ssh2.StreamGobbler; public class SshConnection { private final static String HOSTNAME = "hostname"; private final static String USERNAME = "userid"; private final static String PASSWORD = "pass"; private final static String ENCODE = "UTF-8"; public SshConnection() { } /** * */ public String execCommand(String command) throws AuthenticationExcepiton, ExitStatusExcepiton, IOException { String out = ""; Connection connection = null; Session session = null; try { connection = new Connection(HOSTNAME); connection.connect(); boolean isAuthenticated = connection.authenticateWithPassword(USERNAME, PASSWORD); if (!isAuthenticated) { throw new AuthenticationExcepiton(); } session = connection.openSession(); session.execCommand(command); out = IOUtils.toString(new StreamGobbler(session.getStdout()), ENCODE); if (session.getExitStatus() != 0) { throw new ExitStatusExcepiton("ExitCode: " + session.getExitStatus()); } System.out.println("ExitCode: " + session.getExitStatus() + "\n" + out); } finally { if (session != null) { session.close(); } if (connection != null) { connection.close(); } } return out; } } import java.io.IOException; /** * */ public class AuthenticationExcepiton extends IOException { public AuthenticationExcepiton() { super("Authentication failed."); } } import java.io.IOException; public class ExitStatusExcepiton extends IOException { public ExitStatusExcepiton() { super(); } /** * */ public ExitStatusExcepiton(String msg) { super(msg); } }
トップ 一覧 検索 最終更新 バックアップ   ヘルプ   最終更新のRSS

Modified by MT22(Moriwaki Takashi)

"PukiWiki" 1.3.7 Copyright © 2001,2002,2003 PukiWiki Developers Team. License is GNU/GPL.
Based on "PukiWiki" 1.3 by sng
Powered by PHP 7.4.28

HTML convert time to 0.008 sec.