需要先導入ssh bulid包,方法如下:
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
public String execute(String ip, String cmd) {
String username = "root";
String password = "password";
try {
// 創建連接
Connection conn = new Connection ( ip, 22 );
// 啟動連接
conn.connect ();
// 驗證用戶密碼
conn.authenticateWithPassword ( username, password );
Session session = conn.openSession ();
//執行命令
session.execCommand ( cmd );
InputStream stdout = new StreamGobbler ( session.getStdout () );
BufferedReader br = new BufferedReader ( new InputStreamReader ( stdout ) );
StringBuffer buffer = new StringBuffer ();
String line;
while ((line = br.readLine ()) != null) {
buffer.append ( line + "\n" );
}
String result = buffer.toString ();
session.close ();
conn.close ();
//如果沒有異常,返回結果為命令執行結果,如果有異常,返回null
return result;
} catch (IOException e) {
e.printStackTrace ();
return null;
}
}
也可以把redline()讀取換成read(),從一行行讀取變成按字符讀取:
InputStream stdout = new StreamGobbler ( session.getStdout () );
StringBuffer buffer = new StringBuffer ();
byte[] bs = new byte[1024 * 16];
while(true) {
int count = stdout.read(bs);
if(count == -1) {
break;
} else {
buffer.append(new String(bs, 0, count));
}
}
stdout.close();
String result = buffer.toString ();