欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java中通過jsch來連接遠(yuǎn)程服務(wù)器執(zhí)行l(wèi)inux命令

 更新時(shí)間:2016年03月04日 17:07:55   作者:孫琛斌  
這篇文章主要介紹了Java中通過jsch來連接遠(yuǎn)程服務(wù)器執(zhí)行l(wèi)inux命令的相關(guān)資料,需要的朋友可以參考下

有時(shí)候你可能需要通過代碼來控制執(zhí)行l(wèi)inux命令實(shí)現(xiàn)某些功能。

針對這類問題可以使用JSCH來實(shí)現(xiàn),具體代碼如下:

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();
}
}
/**
* 連接遠(yuǎn)程服務(wù)器
* @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(); // 創(chuàng)建JSch對象
session = jsch.getSession(userName, host, port); // 根據(jù)用戶名,主機(jī)ip,端口獲取一個(gè)Session對象
session.setPassword(password); // 設(shè)置密碼
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config); // 為Session對象設(shè)置properties
session.setTimeout(timeout); // 設(shè)置timeout時(shí)間
session.connect(); // 通過Session建立鏈接
}
/**
* 在遠(yuǎn)程服務(wù)器上執(zhí)行命令
* @param cmd 要執(zhí)行的命令字符串
* @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();
}
}

相關(guān)文章

最新評論