JSch:纯JAVA实现远程执行SSH2主机的SHELL命令
2013-06-13 23:05
1016 查看
上篇文章我编写了利用JSch实现SFTP的文件上传和下载 /article/3501143.html,在本篇文章中,我将描述如何利用JSch实现执行远程SSH2主机的SHELL命令,不说了,直接上代码和详细的代码说明:
利用JSch实现执行远程SSH2主机的SHELL命令,见我的博文:/article/3501144.html
/** * 利用JSch包实现远程主机SHELL命令执行 * @param ip 主机IP * @param user 主机登陆用户名 * @param psw 主机登陆密码 * @param port 主机ssh2登陆端口,如果取默认值,传-1 * @param privateKey 密钥文件路径 * @param passphrase 密钥的密码 */ public static void sshShell(String ip, String user, String psw ,int port ,String privateKey ,String passphrase) throws Exception{ Session session = null; Channel channel = null; JSch jsch = new JSch(); //设置密钥和密码 if (privateKey != null && !"".equals(privateKey)) { if (passphrase != null && "".equals(passphrase)) { //设置带口令的密钥 jsch.addIdentity(privateKey, passphrase); } else { //设置不带口令的密钥 jsch.addIdentity(privateKey); } } if(port <=0){ //连接服务器,采用默认端口 session = jsch.getSession(user, ip); }else{ //采用指定的端口连接服务器 session = jsch.getSession(user, ip ,port); } //如果服务器连接不上,则抛出异常 if (session == null) { throw new Exception("session is null"); } //设置登陆主机的密码 session.setPassword(psw);//设置密码 //设置第一次登陆的时候提示,可选值:(ask | yes | no) session.setConfig("StrictHostKeyChecking", "no"); //设置登陆超时时间 session.connect(30000); try { //创建sftp通信通道 channel = (Channel) session.openChannel("shell"); channel.connect(1000); //获取输入流和输出流 InputStream instream = channel.getInputStream(); OutputStream outstream = channel.getOutputStream(); //发送需要执行的SHELL命令,需要用\n结尾,表示回车 String shellCommand = "ls \n"; outstream.write(shellCommand.getBytes()); outstream.flush(); //获取命令执行的结果 if (instream.available() > 0) { byte[] data = new byte[instream.available()]; int nLen = instream.read(data); if (nLen < 0) { throw new Exception("network error."); } //转换输出结果并打印出来 String temp = new String(data, 0, nLen,"iso8859-1"); System.out.println(temp); } outstream.close(); instream.close(); } catch (Exception e) { e.printStackTrace(); } finally { session.disconnect(); channel.disconnect(); } }
利用JSch实现执行远程SSH2主机的SHELL命令,见我的博文:/article/3501144.html
相关文章推荐
- JSch:纯JAVA实现远程执行SSH2主机的SHELL命令
- JSch:纯JAVA实现远程执行SSH2主机的SHELL命令
- JSch:纯JAVA实现远程执行SSH2主机的SHELL命令
- JSch:纯JAVA实现远程执行SSH2主机的SHELL命令
- 纯JAVA实现远程执行SSH2主机的SHELL命令
- JAVA实现远程执行SSH2主机的SHELL命令
- java中使用JSCH包,SFTP及SSH2文件操作及远程命令执行(改进)
- java中使用JSCH包,SFTP及SSH2文件操作及远程命令执行
- java中利用jsch执行远程命令,实现sftp
- java jsch远程执行shell脚本命令
- Java实现远程联接服务器执行shell命令
- windows 下 java程序jsch连接远程linux服务器执行shell命令
- shell脚本实现同时多台远程主机执行命令的代码分享
- java中使用JSCH包,SFTP及SSH2文件操作及远程命令执行
- java通过ssh2远程连接计算机并执行linux命令的方法(转)
- Java SSH远程执行Shell脚本实现
- jenkins结合shell实现登录远程主机执行shell脚本
- java实现ssh登录执行shell命令及一些问题。
- java本地调用cmd,shell命令,远程调用Linux执行命令方法总结
- java本地调用cmd,shell命令,远程调用Linux执行命令方法总结