當(dāng)前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
JSch:纯JAVA实现远程执行SSH2主机的SHELL命令
生活随笔
收集整理的這篇文章主要介紹了
JSch:纯JAVA实现远程执行SSH2主机的SHELL命令
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
http://txy821.iteye.com/blog/1405230
?
http://my.oschina.net/hetiangui/blog/137426
上篇文章我編寫了利用JSch實(shí)現(xiàn)SFTP的文件上傳和下載?http://my.oschina.net/hetiangui/blog/137357,在本篇文章中,我將描述如何利用JSch實(shí)現(xiàn)執(zhí)行遠(yuǎn)程SSH2主機(jī)的SHELL命令,不說了,直接上代碼和詳細(xì)的代碼說明:
| 01 | /** |
| 02 | ?* 利用JSch包實(shí)現(xiàn)遠(yuǎn)程主機(jī)SHELL命令執(zhí)行 |
| 03 | ?* @param ip 主機(jī)IP |
| 04 | ?* @param user 主機(jī)登陸用戶名 |
| 05 | ?* @param psw? 主機(jī)登陸密碼 |
| 06 | ?* @param port 主機(jī)ssh2登陸端口,如果取默認(rèn)值,傳-1 |
| 07 | ?* @param privateKey 密鑰文件路徑 |
| 08 | ?* @param passphrase 密鑰的密碼 |
| 09 | ?*/ |
| 10 | public static void sshShell(String ip, String user, String psw |
| 11 | ????????,int port ,String privateKey ,String passphrase) throws Exception{ |
| 12 | ????Session session = null; |
| 13 | ????Channel channel = null; |
| 14 | ? |
| 15 | ?????? |
| 16 | ????JSch jsch = new JSch(); |
| 17 | ? |
| 18 | ????//設(shè)置密鑰和密碼 |
| 19 | ????if (privateKey != null && !"".equals(privateKey)) { |
| 20 | ????????if (passphrase != null && "".equals(passphrase)) { |
| 21 | ????????????//設(shè)置帶口令的密鑰 |
| 22 | ????????????jsch.addIdentity(privateKey, passphrase); |
| 23 | ????????} else { |
| 24 | ????????????//設(shè)置不帶口令的密鑰 |
| 25 | ????????????jsch.addIdentity(privateKey); |
| 26 | ????????} |
| 27 | ????} |
| 28 | ?????? |
| 29 | ????if(port <=0){ |
| 30 | ????????//連接服務(wù)器,采用默認(rèn)端口 |
| 31 | ????????session = jsch.getSession(user, ip); |
| 32 | ????}else{ |
| 33 | ????????//采用指定的端口連接服務(wù)器 |
| 34 | ????????session = jsch.getSession(user, ip ,port); |
| 35 | ????} |
| 36 | ? |
| 37 | ????//如果服務(wù)器連接不上,則拋出異常 |
| 38 | ????if (session == null) { |
| 39 | ????????throw new Exception("session is null"); |
| 40 | ????} |
| 41 | ?????? |
| 42 | ????//設(shè)置登陸主機(jī)的密碼 |
| 43 | ????session.setPassword(psw);//設(shè)置密碼??? |
| 44 | ????//設(shè)置第一次登陸的時(shí)候提示,可選值:(ask | yes | no) |
| 45 | ????session.setConfig("StrictHostKeyChecking", "no"); |
| 46 | ????//設(shè)置登陸超時(shí)時(shí)間??? |
| 47 | ????session.connect(30000); |
| 48 | ?????????? |
| 49 | ????try { |
| 50 | ????????//創(chuàng)建sftp通信通道 |
| 51 | ????????channel = (Channel) session.openChannel("shell"); |
| 52 | ????????channel.connect(1000); |
| 53 | ? |
| 54 | ????????//獲取輸入流和輸出流 |
| 55 | ????????InputStream instream = channel.getInputStream(); |
| 56 | ????????OutputStream outstream = channel.getOutputStream(); |
| 57 | ?????????? |
| 58 | ????????//發(fā)送需要執(zhí)行的SHELL命令,需要用\n結(jié)尾,表示回車 |
| 59 | ????????String shellCommand = "ls \n"; |
| 60 | ????????outstream.write(shellCommand.getBytes()); |
| 61 | ????????outstream.flush(); |
| 62 | ? |
| 63 | ? |
| 64 | ????????//獲取命令執(zhí)行的結(jié)果 |
| 65 | ????????if (instream.available() > 0) { |
| 66 | ????????????byte[] data = new byte[instream.available()]; |
| 67 | ????????????int nLen = instream.read(data); |
| 68 | ?????????????? |
| 69 | ????????????if (nLen < 0) { |
| 70 | ????????????????throw new Exception("network error."); |
| 71 | ????????????} |
| 72 | ?????????????? |
| 73 | ????????????//轉(zhuǎn)換輸出結(jié)果并打印出來 |
| 74 | ????????????String temp = new String(data, 0, nLen,"iso8859-1"); |
| 75 | ????????????System.out.println(temp); |
| 76 | ????????} |
| 77 | ????????outstream.close(); |
| 78 | ????????instream.close(); |
| 79 | ????} catch (Exception e) { |
| 80 | ????????e.printStackTrace(); |
| 81 | ????} finally { |
| 82 | ????????session.disconnect(); |
| 83 | ????????channel.disconnect(); |
| 84 | ????} |
| 85 | } |
利用JSch實(shí)現(xiàn)執(zhí)行遠(yuǎn)程SSH2主機(jī)的SHELL命令,見我的博文:http://my.oschina.net/hetiangui/blog/137426
==========================
java程序通過密鑰方式使用JSch API訪問SSH(轉(zhuǎn)帖)
- 博客分類:
- SFTP
2011-05-09 20:44 297人閱讀 評(píng)論(0) 收藏 舉報(bào)
java程序通過密鑰方式使用JSch API訪問SSH
2010-05-20 14:51
上面已經(jīng)驗(yàn)證了通過密鑰方式訪問SSH Server是可行的,并且給自己搭建了一個(gè)測試環(huán)境,下面就開始我最終的目的:java程序通過密鑰訪問。
1、工程引入jsch-0.1.42.jar,可以到http://www.jcraft.com/jsch/官方下載。
2、在官方的example中,有一個(gè)demo,類UserAuthPubKey,是使用密鑰訪問的,參考了下,我對(duì)其進(jìn)行了修改,改為自動(dòng)連接并使用SFTP協(xié)議顯示當(dāng)前路徑,代碼如下:
package Test.sftp;
import com.jcraft.jsch.*;
public class TestKeyAcc {
public static void main(String[] arg) {
?? String keyFile = "./id_rsa";
?? String user = "username";
?? String host = "127.0.0.1";
?? String passphrase = "111111";
?? int port = 22;
?? try {
??? JSch jsch = new JSch();
??? jsch.addIdentity(keyFile);
??? Session session = jsch.getSession(user, host, port);
??? // username and passphrase will be given via UserInfo interface.
??? UserInfo ui = new MyUserInfo(passphrase);
??? session.setUserInfo(ui);
??? session.connect();
??? Channel channel = session.openChannel("sftp");
??? channel.connect();
??? ChannelSftp sftp = (ChannelSftp) channel;
??? System.out.println(sftp.pwd());
?? } catch (Exception e) {
??? e.printStackTrace();
??? System.out.println(e);
?? }
}
public static class MyUserInfo implements UserInfo {
?? private String passphrase = null;
?? public MyUserInfo(String passphrase) {
??? this.passphrase = passphrase;
?? }
?? public String getPassphrase() {
??? return passphrase;
?? }
?? public String getPassword() {
??? return null;
?? }
?? public boolean promptPassphrase(String s) {
??? return true;
?? }
?? public boolean promptPassword(String s) {
??? return true;
?? }
?? public boolean promptYesNo(String s) {
??? return true;
?? }
?? public void showMessage(String s) {
??? System.out.println(s);
?? }
}
}
運(yùn)行后結(jié)果顯示:
??????????????????????????? ****USAGE WARNING****
This is a private computer system. This computer system, including all
related equipment, networks, and network devices (specifically including
Internet access) are provided only for authorized use. This computer system
may be monitored for all lawful purposes, including to ensure that its use
is authorized, for management of the system, to facilitate protection against
unauthorized access, and to verify security procedures, survivability, and
operational security. Monitoring includes active attacks by authorized entities
to test or verify the security of this system. During monitoring, information
may be examined, recorded, copied and used for authorized purposes. All
information, including personal information, placed or sent over this system
may be monitored.
Use of this computer system, authorized or unauthorized, constitutes consent
to monitoring of this system. Unauthorized use may subject you to criminal
prosecution. Evidence of unauthorized use collected during monitoring may be
used for administrative, criminal, or other adverse action. Use of this system
constitutes consent to monitoring for these purposes.
/cygdrive/d/opensshhome/username
ok,good,問題解決了,如果不是密鑰方式,與普通FTP一樣的用戶名及密碼訪問又是怎樣的呢,那就比較簡單了
去掉
?? jsch.addIdentity(keyFile);
及
??? UserInfo ui = new MyUserInfo(passphrase);
??? session.setUserInfo(ui);
在Session sshSession = jsch.getSession(userStr, serverIp, port);下增加
????????? sshSession.setPassword(passwordStr);
如果在生成私鑰時(shí)沒有使用密碼,那又是怎樣的呢?其實(shí)很簡單,如果不需要密碼訪問,你提供了密碼也是通過的( new MyUserInfo(passphrase);中密碼不null或空),大概過程是,先看是否需要密碼,如果不需要,那么就直接過去,所以即便設(shè)置了密碼也沒問題。
在使用該API進(jìn)行密鑰及非密鑰訪問SFTP時(shí),感覺不是很愜意,試驗(yàn)了許久才通過。
以上文字但愿對(duì)后來者有所幫助
?
==============
http://www.jcraft.com/jsch/examples/
- Shell.java
demonstrating how to connect to sshd server and get the shell prompt. - Exec.java
demonstrating the remote exec. - ViaHTTP.java
demonstrating the ssh session via HTTP proxy. - ViaSOCKS.java
demonstrating the ssh session via SOCKS proxy. - PortForwardingR.java
demonstrating the port forwarding like option -R of ssh command. - PortForwardingL.java
demonstrating the port forwarding like option -L of ssh command. - StreamForwarding.java
demonstrating the stream forwarding. - UserAuthPubKey.java
demonstrating the user authentification by public key. - Compression.java
demonstrating the packet compression. - ScpTo.java
demonstrating the file transfer from local to remote. - ScpFrom.java
demonstrating the file transfer from remote to local - Sftp.java
demonstrating the sftp protocol support. - KnownHosts.java
demonstrating the 'known_hosts' file handling. - UserAuthKI.java
demonstrating the keyboard-interactive authentication. - KeyGen.java
demonstrating the DSA keypair generation. - ChangePassphrase.java
demonstrating how to change the passphrase for a private key file instead of creating a new private key. - AES.java
demonstrating how to use "aes128-cbc". - Daemon.java
demonstrating how to provide a network service like inetd by using remote port-forwarding functionality. - Logger.java
demonstrating how to enable logging mechanism and get logging messages. - Subsystem.java
demonstrating how to use the Subsystem channel. - Sudo.java
demonstrating how to sudo on the remote. - ScpToNoneCipher.java
demonstrating how to enable none cipher. - X11Forwarding.java
demonstrating the X11 forwarding. - JumpHosts.java
demonstrating SSH through jump hosts. - OpenSSHConfig.java
demonstrating how OpenSSH's config is supported.
?
總結(jié)
以上是生活随笔為你收集整理的JSch:纯JAVA实现远程执行SSH2主机的SHELL命令的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 深入理解connect by
- 下一篇: 深入浅出JSONP--解决ajax跨域问