ChannelShell,ChannelExec和ChannelSftp区别以及使用

ChannelShell、ChannelExec、ChannelSftp,前两类用于执行命令(命令可以是shell语句,也可以是python xxx.py),后一种是用于上传下载文件。

ChannelShell和ChannelExec的区别: 前者是交互式的,在channel.connect()之前,需要获取outputStream和inputStream,然后outputstream发送命令,从instream中读取命令的结果(注意,发送命令之后,读取命令之前要等待一会儿,一般需要写个循环判断,每秒读一次,根据实际情况设置xx秒超时退出),但是有个坏处是,它执行就像登陆到vm上打印的信息一样,无论执行命令后的任何信息,它都会通过instream返回到客户端来,而你可能仅仅需要命令执行后的结果;于是就有了后者,非交互的,一次通道执行一条命令(当然如果你组合的好,也可以多条,反正就是一个字符串,一次交互,偷偷的告诉你,这一个python脚本,下发的命令去执行这个脚本,可以做好多好多事情哦),好处是,它返回的信息非常干净,只返回标准输出,标准错误是不返回的,这时你可以利用python的print,正确时你print正确信息,错误时print错误信息,客户端都能获取到结果啦(因为print是标准输出)。

ChannelShell用法

String command = "nohup bash /home/aa.sh  " + partm.toString();
try {
			JSch jsch = new JSch();
			com.jcraft.jsch.Session sshSession = jsch.getSession("服务器用户","服务器ip", 22);
			sshSession.setPassword("服务器密码");
			java.util.Properties config = new java.util.Properties();
			config.put("StrictHostKeyChecking", "no");
			sshSession.setConfig(config);
			sshSession.connect();
			ChannelShell shell = (ChannelShell) sshSession.openChannel("shell");
			InputStream inputStream = shell.getInputStream();
			OutputStream outputStream = shell.getOutputStream();
			PrintWriter printWriter = new PrintWriter(outputStream);
			shell.setPty(true);
			shell.connect();
			printWriter.println(command);
			printWriter.println("exit");// 加上个就是为了,结束本次交互
			printWriter.flush();
			outputStream.flush();
			BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
			String msg = null;
			while ((msg = in.readLine()) != null) {
				System.out.println(msg);
			}
			in.close();
			gen_cgsnpWMapper.updateByPrimaryKeySelective(gen_cgsnp);
		} catch (JSchException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

ChannelExec用法
		String resultJson = null;
		ChannelExec channelExec = null;
		if (command != null) {
			try {
				JSch jsch = new JSch();
				// 获取sshSession
				Session session = jsch.getSession("服务器用户", "服务器ip", "服务器端口号");
				// 添加密码
				session.setPassword("服务器密码");
				Properties sshConfig = new Properties();
				// 严格主机密钥检查
				sshConfig.put("StrictHostKeyChecking", "no");
				session.setConfig(sshConfig);
				// 开启sshSession连接
				session.connect();
				channelExec = (ChannelExec) session.openChannel("exec");
				// 设置需要执行的shell命令
				channelExec.setCommand(command);
				lg.info("linux命令:" + command);
				channelExec.setInputStream(null);
				channelExec.setErrStream(System.err);
				channelExec.connect();
			} catch (JSchException e) {
				e.printStackTrace();
			} finally {
				if (null != channelExec) {
					channelExec.disconnect();
				}
			}
		}


ChannelSftp用法
		ChannelSftp sftp = null;
		StringBuffer buffer = new StringBuffer();
		try {
			JSch jsch = new JSch();
				// 获取sshSession
				Session session = jsch.getSession("服务器用户", "服务器ip", "服务器端口号");
				// 添加密码
				session.setPassword("服务器密码");
				Properties sshConfig = new Properties();
				// 严格主机密钥检查
				sshConfig.put("StrictHostKeyChecking", "no");
				session.setConfig(sshConfig);
				// 开启sshSession连接
				session.connect();
			// 获取sftp通道
			Channel channel = session.openChannel("sftp");
			// 开启
			channel.connect();
			sftp = (ChannelSftp) channel;
			lg.info("Connected to " + host + ".");
			// 获取生成文件流
			InputStream inputStream = sftp.get("读取文件路径");
			BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
			String line = "";
			while ((line = in.readLine()) != null) {
				buffer.append(line);
			}
			// 关闭流
			inputStream.close();
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (JSchException e) {
			e.printStackTrace();
		} catch (SftpException e) {
			e.printStackTrace();
		} finally {
			if (null != sftp) {
				sftp.quit();
			}
			closeSession();
		}
		return buffer.toString();
  • 3
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Java使用ChannelShell可以通过JSch库来实现。JSch库是一个Java实现的SSH2协议的库,通过它可以连接到SSH服务器,并执行相关的命令。以下是一个简单的使用ChannelShell的示例代码: ```java import com.jcraft.jsch.*; public class ChannelShellExample { public static void main(String[] arg) { try { JSch jsch = new JSch(); String host = "hostname"; String user = "username"; String password = "password"; Session session = jsch.getSession(user, host, 22); session.setPassword(password); session.setConfig("StrictHostKeyChecking", "no"); session.connect(); System.out.println("Connected"); Channel channel = session.openChannel("shell"); // Set the OutputStream of the channel to System.out channel.setOutputStream(System.out); // Connect the channel to start receiving data channel.connect(); // Send commands to the channel ((ChannelShell) channel).setPty(true); ((ChannelShell) channel).setPtyType("vt220"); ((ChannelShell) channel).setEnv("TERM", "vt220"); // Send the exit command to the channel ((ChannelShell) channel).sendSignal("exit"); // Wait for the channel to complete channel.waitForEnd(); // Disconnect the channel and session channel.disconnect(); session.disconnect(); } catch (Exception e) { System.out.println(e); } } } ``` 在上面的代码中,我们通过JSch库连接到SSH服务器,并打开一个shell通道。我们设置了输出流为System.out,这样就可以在控制台中看到收到的数据。然后我们通过sendSignal方法发送了一个exit信号给shell通道,这样就可以退出通道。最后我们断开了通道和会话。 需要注意的是,这段代码只是一个简单的示例,实际使用时需要根据具体情况进行修改。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值