Ganymed SSH-2 for Java Learning notes

Source: Internet
Author: User
Tags touch command ssh server

What is ganymed SSH-2 for Java

Ganymed SSH-2 for Java is a package that implements the SSH-2 protocol with pure Java. You can use it to connect to the SSH server directly in the Java program. Official website address for http://www.ganymed.ethz.ch/ssh2/can see the last update log for 2006, is a more ancient tool. Here's a look at what this tool can do.

Environment Ready Linux Server preparation

During the test, a Ubuntu virtual machine was installed on this machine, and the openssh-server is required to install because the machine does not have an SSH server.

    • Update under System Tools and dependencies

      sudo apt-get update;
    • Execute the Install command

      sudo apt-get install openssh-server openssh-client

After the installation is complete, you can sudo ps -e |grep ssh check to see if SSH is running. If the result exists sshd then the SSH service is already running. You can sudo service ssh start start the SSH service by doing this.

After configuring the SSH service, you can connect to the Linux machine via the terminal ssh of the local machine.

Java Code connection test SSH login remote machine test
import ch.ethz.ssh2.Connection;import ch.ethz.ssh2.Session;import Ch.ethz.ssh2.StreamGobbler; Public classBasic { Public Static void Main(string[] args) {String hostname ="192.168.1.101";//remote machine IPString username ="SSS";//Login user nameString Password ="123456";//Login Password        Try{Connection conn =NewConnection (hostname); Conn.Connect();Booleanisauthenticated = conn.Authenticatewithpassword(username, password);/// Whether login is successful            if(IsAuthenticated = =false) {Throw NewIOException ("authentication failed."); } Session sess = conn.opensession();//execute commandSess.execcommand("uname-a && date && uptime && who"); System. out.println("Here's some information about the remote host:"); InputStream stdout =New Streamgobbler(Sess.Getstdout()); BufferedReader br =NewBufferedReader (NewInputStreamReader (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());//Close connectionSess.Close(); Conn.Close(); }Catch(IOException e) {e.Printstacktrace(System.Err); System.Exit(2); }    }}

The result of the above code execution is as follows:

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
Deleting files from the server

Create a new file by performing the touch command in the user directory of the server
touch test.txt

//...建立连接boolean isAuthenticated = conn.authenticateWithPassword(username, password);  iffalse)  {     thrownew IOException("Authentication failed."); }System.out.println("连接服务器成功!"newSFTPv3Client(conn);sftpClient.rm("/home/sss/test.txt");//删除文件sftpClient.close();//。。。关闭连接

If the file to be deleted does not exist, the following exception is thrown

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)
Delete a folder from the server
//。。。建立连接newSFTPv3Client(conn);sftpClient.rmdir("/home/sss/test/");//删除文件夹  Remove an empty directorysftpClient.close();//。。。关闭连接

Note that the above method of deleting a folder can only delete empty folders. If you want to delete a non-empty folder, you need to use a different method.

Remove a non-empty folder from the server

Use the Touch command and the mkdir command to create some files and subfolders in the user directory on the server.

//。。。建立连接" rm -rf /home/sss/test";Session session = conn.openSession();  session.execCommand(cmd); session.close();//。。。关闭连接

You can directly execute the RM-RF command to delete a non-empty folder. Of course, there are other ways to refer to http://blog.csdn.net/column/details/13576.html

Downloading files from the server
//。。。建立连接newSCPClient(conn);//从服务器下载文件client.get("/home/sss/sss.txt""/Users/sss/");//。。。关闭连接
Uploading files to the server
//。。。建立连接newSCPClient(conn);//上传文件至服务器client.put("/Users/sss/s.txt""/home/sss/");//。。。关闭连接

The above is the use of some basic commands, through the combination of some commonly used operations command can be implemented by an operation and maintenance system functions.

Ganymed SSH-2 for Java Learning notes

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.