Java에서 jsch를 통해 원격 서버에 연결하여 linux 명령을 실행합니다

2203 단어 jsch실행명령
때때로 코드를 통해 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();
}
}

좋은 웹페이지 즐겨찾기