Java中通過jsch來連線遠端伺服器執行linux命令
阿新 • • 發佈:2019-01-10
有時候你可能需要通過程式碼來控制執行linux命令實現某些功能。
針對這類問題可以使用JSCH來實現,具體程式碼如下:
public class CogradientImgFileManager{
private static final Logger log = LoggerFactory.getLogger(CogradientImgFileManager.class);
private static ChannelExec channelExec;
private static Session session = null ;
private static int timeout = 60000;
// 測試程式碼
public static void main(String[] args){
try{
versouSshUtil("10.8.12.189","jmuser","root1234",22);
runCmd("java -version","UTF-8");
}catch (Exception e){
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 連線遠端伺服器
* @param host ip地址
* @param userName 登入名
* @param password 密碼
* @param port 埠
* @throws Exception
*/
public static void versouSshUtil(String host,String userName,String password,int port) throws Exception{
log.info("嘗試連線到....host:" + host + ",username:" + userName + ",password:" + password + ",port:"
+ port);
JSch jsch = new JSch(); // 建立JSch物件
session = jsch.getSession(userName, host, port); // 根據使用者名稱,主機ip,埠獲取一個Session物件
session.setPassword(password); // 設定密碼
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config); // 為Session物件設定properties
session.setTimeout(timeout); // 設定timeout時間
session.connect(); // 通過Session建立連結
}
/**
* 在遠端伺服器上執行命令
* @param cmd 要執行的命令字串
* @param charset 編碼
* @throws Exception
*/
public static void runCmd(String cmd,String charset) throws Exception{
channelExec = (ChannelExec) session.openChannel("exec");
channelExec.setCommand(cmd);
channelExec.setInputStream(null);
channelExec.setErrStream(System.err);
channelExec.connect();
InputStream in = channelExec.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in, Charset.forName(charset)));
String buf = null;
while ((buf = reader.readLine()) != null){
System.out.println(buf);
}
reader.close();
channelExec.disconnect();
}
}