日期:2014-5-16 浏览次数:20080次

java远程登录linux并调用shell命令
java程序用ssh远程登录linux并调用shell命令,需要用到java的ssh客户端,这里使用的是JSch,支持ssh2

示例代码登录远程linux,返回远程目录中的所有文件

JSch jsch = new JSch();
		try {
			Session session = jsch.getSession(user, host, port);
			session.setPassword(pass);
			session.setTimeout(2000);
			Properties config = new Properties();
			config.put("StrictHostKeyChecking", "no");
			session.setConfig(config);
			session.connect();
			
			Channel channel = session.openChannel("exec");
			ChannelExec execChannel = (ChannelExec)channel;
			execChannel.setCommand("ls");
			InputStream in = channel.getInputStream();
			channel.connect();
			
			StringBuffer sb = new StringBuffer();
			int c = -1;
			while((c = in.read()) != -1){
				sb.append((char)c);
			}
			System.out.println(sb.toString());
			
			channel.disconnect();
			session.disconnect();
		} catch (JSchException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}