java 使用jsch 远程链接linux执行命令
2012-09-04 13:14
791 查看
一个简单的jsch链接linux并执行命令的utils。
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; 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; public class ShellUtils { private static JSch jsch; private static Session session; /** * 连接到指定的IP * * @throws JSchException */ public static void connect(String user, String passwd, String host) throws JSchException { jsch = new JSch(); session = jsch.getSession(user, host, 22); session.setPassword(passwd); java.util.Properties config = new java.util.Properties(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config); session.connect(); } /** * 执行相关的命令 * @throws JSchException */ public static void execCmd(String command, String user, String passwd, String host) throws JSchException { connect(user, passwd, host); BufferedReader reader = null; Channel channel = null; try { while (command != null) { channel = session.openChannel("exec"); ((ChannelExec) channel).setCommand(command); 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) { System.out.println(buf); } } } catch (IOException e) { e.printStackTrace(); } catch (JSchException e) { e.printStackTrace(); } finally { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } channel.disconnect(); session.disconnect(); } } }
相关文章推荐
- java 使用jsch 远程链接linux执行命令
- java 使用jsch 远程链接linux执行命令
- windows 下 java程序jsch连接远程linux服务器执行shell命令
- java中如何使用jsch远程连接linux服务器并执行命令
- java中使用JSCH包,SFTP及SSH2文件操作及远程命令执行
- java中使用JSCH包,SFTP及SSH2文件操作及远程命令执行
- linux 使用java编写ssh登陆主机 输入密码登陆并执行命令(jsch)
- java中使用JSCH包,SFTP及SSH2文件操作及远程命令执行(改进)
- Python 使用paramiko实现远程登录Linux主机并执行命令和操作
- 利用java实现可远程执行linux命令的小工具
- java远程执行linux命令
- java本地调用cmd,shell命令,远程调用Linux执行命令方法总结
- java远程执行linux命令
- java远程执行linux命令
- java使用ssh连接Linux并执行命令
- linux使用java本地执行cd命令问题
- linux下使用ssh远程执行命令批量导出数据库到本地
- java使用ssh连接Linux并执行命令
- 使用JSCH连接Linux服务器-执行linux命令
- java通过代码登录远程linux服务器并执行linux命令