Ganymed SSH-2 for Java學習筆記

來源:互聯網
上載者:User

標籤:x86_64   pass   rmdir   虛擬機器   format   ack   column   username   pcl   

Ganymed SSH-2 for Java 是什麼

Ganymed SSH-2 for Java是用純Java實現SSH-2協議的一個包。可以利用它直接在Java程式中串連SSH伺服器。官網地址為 http://www.ganymed.ethz.ch/ssh2/ 可以看到最後的更新日誌為2006年,是比較古老的一個工具了。下面看看這個工具可以做什麼。

環境準備Linux伺服器準備

測試時在本機上裝了一個Ubuntu的虛擬機器,由於新裝的機器沒有ssh服務端,所以需要先安裝openssh-server。

  • 更新下系統工具和依賴

    sudo apt-get update;
  • 執行安裝命令

    sudo apt-get install openssh-server openssh-client

安裝完成之後可以通過 sudo ps -e |grep ssh 查看ssh是否在運行。如果結果存在sshd則表示ssh服務已經在運行。可以通過 sudo service ssh start 來啟動ssh服務。

配置好ssh服務之後即可通過本地機器的終端ssh串連到linux機器。

Java代碼串連測試ssh登入遠程機器測試
import ch.ethz.ssh2.Connection;import ch.ethz.ssh2.Session;import ch.ethz.ssh2.StreamGobbler;public class Basic {    public static void main(String[] args) {        String hostname = "192.168.1.101";//遠程機器IP        String username = "sss";//登入使用者名稱        String password = "123456";//登入密碼        try {            Connection conn = new Connection(hostname);            conn.connect();            boolean isAuthenticated = conn.authenticateWithPassword(username, password);            ///是否登入成功            if (isAuthenticated == false) {                throw new IOException("Authentication failed.");            }            Session sess = conn.openSession();            //執行命令            sess.execCommand("uname -a && date && uptime && who");            System.out.println("Here is some information about the remote host:");            InputStream stdout = new StreamGobbler(sess.getStdout());            BufferedReader br = new BufferedReader(new InputStreamReader(stdout));            while (true) {                String line = br.readLine();                if (line == null)                    break;                System.out.println(line);            }            /* Show exit status, if available (otherwise "null") */            System.out.println("ExitCode: " + sess.getExitStatus());            //關閉串連            sess.close();            conn.close();        } catch (IOException e) {            e.printStackTrace(System.err);            System.exit(2);        }    }}

以上代碼執行結果如下:

Here is some information about the remote host:Linux sss-VirtualBox 4.13.0-16-generic #19-Ubuntu SMP Wed Oct 11 18:35:14 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux2017年 11月 16日 星期四 19:19:12 CST 19:19:12 up  1:21,  2 users,  load average: 0.00, 0.00, 0.00sss tty2         2017-11-16 17:58 (/dev/tty2)sss pts/1        2017-11-16 18:01 (10.15.233.83)ExitCode: 0
從伺服器刪除檔案

在伺服器的使用者目錄下執行touch命令建立一個檔案
touch test.txt

//...建立串連boolean isAuthenticated = conn.authenticateWithPassword(username, password);  if (isAuthenticated == false)  {     throw new IOException("Authentication failed."); }System.out.println("串連伺服器成功!");SFTPv3Client sftpClient = new SFTPv3Client(conn);sftpClient.rm("/home/sss/test.txt");//刪除檔案sftpClient.close();//。。。關閉串連

如果要刪除的檔案不存在,則會拋出如下異常

ch.ethz.ssh2.SFTPException: No such file (SSH_FX_NO_SUCH_FILE: A reference was made to a file which does not exist.)    at ch.ethz.ssh2.SFTPv3Client.expectStatusOKMessage(SFTPv3Client.java:555)    at ch.ethz.ssh2.SFTPv3Client.rm(SFTPv3Client.java:969)    at ganymed.DeleteServerFile.main(DeleteServerFile.java:25)
從伺服器刪除檔案夾
//。。。建立串連SFTPv3Client sftpClient = new SFTPv3Client(conn);sftpClient.rmdir("/home/sss/test/");//刪除檔案夾  Remove an empty directorysftpClient.close();//。。。關閉串連

注意,以上刪除檔案夾的方法只能刪除空檔案夾。如果要刪除非空檔案夾則需要採用其他方法。

從伺服器刪除非空檔案夾

使用touch命令及mkdir命令在伺服器上使用者目錄下建立一些檔案和子檔案夾。

//。。。建立串連String cmd = " rm -rf /home/sss/test";Session session = conn.openSession();  session.execCommand(cmd); session.close();//。。。關閉串連

可以直接執行rm -rf命令來刪除非空檔案夾。當然,還有別的方法,參考 http://blog.csdn.net/column/details/13576.html

從伺服器下載檔案
//。。。建立串連SCPClient client = new SCPClient(conn);//從伺服器下載檔案client.get("/home/sss/sss.txt", "/Users/sss/");//。。。關閉串連
上傳檔案到伺服器
//。。。建立串連SCPClient client = new SCPClient(conn);//上傳檔案至伺服器client.put("/Users/sss/s.txt", "/home/sss/");//。。。關閉串連

以上為一些基礎命令的用法,通過結合一些常用的營運命令即可實現一個營運系統的功能。

Ganymed SSH-2 for Java學習筆記

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.