该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
这是我在网上找的一段代码,确实可以操作一些linux命令也可以拿到输出结果;但是我在执行命令“ screen -r XXX ”命令的时候,返回结果“Must be connected to a terminal.” ,其实我是想用代码控制终端的远程连接,然后再这个远程连接中执行一些命令,但是不知道如何实现;
用的是jsch这个jar包,没有中文API太费劲了,不知可有过来人帮忙解答一下,不胜感激;
另外这俩方法该怎么用:
channelExec.setPty(true);//虚拟终端???
channelExec.setTerminalMode(terminal_mode);
public static void main(String[] args) throws Exception {
JSch jsch = new JSch(); // 创建JSch对象
String userName = "userName";// 用户名
String password = "password";// 密码
String host = "host";// 服务器地址
int port = 22;// 端口号
String cmd = "screen -r XXX";// 要运行的命令
Session session = jsch.getSession(userName, host, port); // 根据用户名,主机ip,端口获取一个Session对象
session.setPassword(password); // 设置密码
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config); // 为Session对象设置properties
int timeout = 60000;
session.setTimeout(timeout); // 设置timeout时间
session.connect(); // 通过Session建立链接
ChannelExec 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("UTF-8")));
String buf = null;
StringBuffer sb = new StringBuffer();
while ((buf = reader.readLine()) != null) {
sb.append(buf);
System.out.println(buf);// 打印控制台输出
}
reader.close();
channelExec.disconnect();
if (null != session) {
session.disconnect();
}
}