Ganymed SSH-2 for Java系列3之執行遠程shell 命令__Java

來源:互聯網
上載者:User

利用Ganymed SSH-2 for Java 串連到遠程伺服器,然後執行shell命令;


首先我們再在之前CommandRunner類中再添加一個執行shell命令的方法,具體如下所示:


public static String execShellScript(String host, String username,String password,String cmd, int port) throws IOException {if (logger.isInfoEnabled()) {logger.info("running SSH cmd [" + cmd + "]");}Connection conn = null;Session sess = null;InputStream stdout = null;BufferedReader br = null;StringBuffer buffer = new StringBuffer("exec result:");buffer.append(System.getProperty("line.separator"));// 換行try {conn = getOpenedConnection(host, username, password, port);sess = conn.openSession();sess.execCommand(cmd);stdout = new StreamGobbler(sess.getStdout());br = new BufferedReader(new InputStreamReader(stdout));while (true) {// attention: do not comment this block, or you will hit// NullPointerException// when you are trying to read exit statusString line = br.readLine();if (line == null)break;buffer.append(line);buffer.append(System.getProperty("line.separator"));// 換行if (logger.isInfoEnabled()) {logger.info(line);}}} finally {sess.close();conn.close();}return buffer.toString();}


測試代碼:

public static void main(String[] args) {String cmd = "uname -a";try {String info = CommandRunner.execShellScript("172.16.18.141", "root","123456",cmd,22);System.out.println("info is:"+info);} catch (IOException e) {e.printStackTrace();}}



執行結果

log4j:WARN No appenders could be found for logger (com.ssh2.shell.ganymed.CommandRunner).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
info is:exec result:
Linux localhost.localdomain 2.6.32-220.el6.x86_64 #1 SMP Wed Nov 9 08:03:13 EST 2011 x86_64 x86_64 x86_64 GNU/Linux

至此,串連遠程伺服器執行shell命令簡單方法就實現了。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.