java 使用jsch 遠程鏈接linux執行命令

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;


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






public class ShellUtils {
private static JSch jsch;
private static Session session;



/**
* 連接到指定的IP

* @throws JSchException
*/
public static void connect(String user, String passwd, String host) throws JSchException {
jsch = new JSch();
session = jsch.getSession(user, host, 22);
session.setPassword(passwd);

java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);

session.connect();
}


/**
* 執行相關的命令
* @throws JSchException 
*/
public static void execCmd(String command, String user, String passwd, String host) throws JSchException {
connect(user, passwd, host);

BufferedReader reader = null;
Channel channel = null;


try {

while (command != null) {

/*exec爲cmd執行命令;shell爲調用shell命令*/

channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(command);

channel.setInputStream(null);
((ChannelExec) channel).setErrStream(System.err);


channel.connect();
InputStream in = channel.getInputStream();
reader = new BufferedReader(new InputStreamReader(in));
String buf = null;
while ((buf = reader.readLine()) != null) {
System.out.println(buf);
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSchException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
channel.disconnect();
session.disconnect();
}
}
   
}
發佈了57 篇原創文章 · 獲贊 26 · 訪問量 51萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章