java 使用jsch 远程链接linux并执行命令

1、连接远程linux,执行命令

 

 

<dependency>
			<groupId>com.jcraft</groupId>
			<artifactId>jsch</artifactId>
			<version>0.1.54</version>
		</dependency>
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

部分代码:


String cmd = "echo 'i love u' >/a.txt";

			BufferedReader reader = null;
			Channel channel = null;
			Session session = null;


try {
						JSch jsch = new JSch();
						session = jsch.getSession(username,host, 22);//22 默认端口
						session.setConfig("PreferredAuthentications", "password");//固定配置,说明验证方法
						session.setConfig("StrictHostKeyChecking", "no");//固定配置,减少验证
						session.setPassword(password);
						session.connect(3000); // making a connection with timeout.

						channel = session.openChannel("exec");
						((ChannelExec) channel).setCommand(cmd);

						channel.setInputStream(null);
						((ChannelExec) channel).setErrStream(System.err);

						channel.connect();
						InputStream in = channel.getInputStream();
						reader = new BufferedReader(new InputStreamReader(in));
						String buf = null;
						while ((buf = reader.readLine()) != null) {
							getCurrentCall(map, currCallBeanList, CommUtil.stringNoNull(buf).trim());//数据处理
						}
					} catch (Exception e) {
						log.error("查询ip:{}的当前通话出错。", GlobalPreConfig.ctiUrlList.get(j));
						e.printStackTrace();
					} finally {
						try {
							reader.close();
						} catch (IOException e) {
							log.error("查询ip:{}的当前通话出错。", GlobalPreConfig.ctiUrlList.get(j));
							e.printStackTrace();
						}
						channel.disconnect();
						session.disconnect();
					}

 

 

2、连接本机linux,执行命令

 

log.debug("查询本机ip:{}的当前通话开始", GlobalPreConfig.ctiUrlList.get(j));

					boolean isLinux = System.getProperty("os.name").toLowerCase().contains("linux");

					if (isLinux) {
						BufferedReader br = SystemRun.batchRunForCurr(cmd, condMap.get(GlobalConstance.COMPANY_ID));
						String lineStr = "";
						String call_list = "";
						while ((lineStr = br.readLine()) != null) {
							call_list = CommUtil.stringNoNull(lineStr).trim();
							getCurrentCall(condMap, currCallBeanList, call_list);
						}
					}
					log.debug("查询本机ip:{}的当前通话结束", GlobalPreConfig.ctiUrlList.get(j));






/**
	 * 系统命令打包运行
	 *
	 * @param cmd
	 * @return
	 * @throws Exception
	 */
	private static BufferedReader batchRunForCurr(String cmd, Object companyId) throws Exception {
		boolean isLinux = System.getProperty("os.name").toLowerCase().contains("linux");
		if (isLinux) {
			// first write sh file
			String runFileName = "/root/tomcat9.0.31/bin/gw.sh";
			String tomcatDir = System.getProperty("catalina.home");
			if (!StringUtils.isEmpty(tomcatDir)) {
				tomcatDir = tomcatDir.substring(tomcatDir.indexOf("/"));// linux
				// tomcatDir=tomcatDir.substring(tomcat_win.indexOf("\\"));//windows
				runFileName = tomcatDir + "/bin/gw.sh";
			}
			log.info("====>>>>>SH file:" + runFileName + "  System batch run:" + cmd);

			File file = new File(runFileName);
			if (!file.exists()) {
				PrintWriter pw = new PrintWriter(new FileWriter(runFileName));
				pw.println(cmd);
				pw.println("");
				pw.close();
				Process pr = Runtime.getRuntime().exec("chmod +x " + runFileName);
				pr.waitFor();
			}
			// change mod to x
			// run
			Process process = Runtime.getRuntime().exec("sh " + runFileName);
			process.waitFor();
			InputStream inStreams = process.getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(inStreams));
			StreamGobbler errorGobbler = new StreamGobbler(process.getErrorStream(), "ERROR");
			errorGobbler.start();
			StreamGobbler outGobbler = new StreamGobbler(process.getInputStream(), "STDOUT");
			outGobbler.start();

			return br;
		} else {
			return null;
		}
	}

 

3、简洁方法:

 

//                    String res = JschUtil.exec(session, cmd, CharsetUtil.CHARSET_UTF_8);
//                    JschUtil.close(session);

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值