1. 程式人生 > >如何通過ssh登入伺服器執行linux指令-ganymed的簡單使用(一)

如何通過ssh登入伺服器執行linux指令-ganymed的簡單使用(一)

ganymed是用java實現的一個ssh協議包.通過他可以直接在java程式中連線ssh伺服器並執行指令.
使用步驟如下:
1.建立Connection:
  Connection connection = new Connection("192.168.73.246").
2.驗證是否可以登入伺服器:
  boolean isAuthenticated = conn.authenticateWithPassword(username, password).true表示登陸成功,false表示登陸失敗.
3.建立session,並執行指令:
  Session session = conn.openSession();
  session.execCommand("cd /home").
4.接收伺服器上控制檯的返回結果:
  InputStream is = new StreamGobbler(session.getStdout());
  InputStreamReader isr = new InputStreamReader(is);
  BufferedReader br = new BufferedReader(isr);
5.獲取指令是否成功執行:0-成功,非0-失敗.
  System.out.println("ExitCode: " + sess.getExitStatus());
6.關閉session和connection.
  sess.close();

  conn.close();

下面通過一個小例子來簡單學習一下如何通過ganymed實現連線ssh伺服器並執行指令.

1.直接看工具類:

<span style="font-size:12px;">package com.ilucky.ssh.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;

/**
 * @author IluckySi
 * @date 20140805
 */
public class SshUtil {

	private Connection connection;

	public SshUtil(SshSetting sshSetting) {
		try {
			//判斷SshSetting中的引數是否為空.
			String ip = sshSetting.getIp();
			String username = sshSetting.getUsername();
			String password = sshSetting.getPassword();
			if (ip == null || username == null || password == null) {
				throw new Exception("SshSetting引數: ip, username和password不能為空!");
			}
			
			//判斷Ssh伺服器是否可以登入.
			connection = new Connection(ip);
			connection.connect();
			boolean isAuthenticated = connection.authenticateWithPassword(username, password);
			if (!isAuthenticated) {
				throw new Exception("SshSetting引數: username和password不正確!");
			}
		} catch (Exception e) {
			System.out.println("獲取Connection發生問題!");
		}
	}

	public String execute(String command) {
		StringBuffer sb = new StringBuffer();
		Session session = null;
		InputStream is  = null;
		InputStreamReader isr = null;
		BufferedReader br = null;
		try {
			//獲取Session會話並執行指令.
			session = connection.openSession();
			session.execCommand(command);
			
			//獲取伺服器上控制檯的返回結果並編碼為UTF-8.
			is = new StreamGobbler(session.getStdout());
			isr = new InputStreamReader(is, Charset.forName("UTF-8"));
			br = new BufferedReader(isr);
			
			//將伺服器返回結果拼接成StringBuffer並返回.
			String buffer = br.readLine();
			while ((buffer = br.readLine()) != null) {
				if (buffer != null) {
					sb.append(buffer.toString() + "\n");
				}
			}
			
			//獲取指令在Ssh伺服器上是否執行成功.
			if(session.getExitStatus() == 0) {
				System.out.println(command + "執行成功!");
			} else {
				System.out.println(command + "執行失敗!");
			}
		} catch (Exception e) {
			System.out.println("執行指令: " + command + "發生問題!");
		} finally {
			try {
				if(br != null) {
					br.close();
					br = null;
				}
				if(isr != null) {
					isr.close();
					isr = null;
				}
				if(is != null) {
					is.close();
					is = null;
				}
				if(session != null) {
					session.close();
					session = null;
				}
			} catch (Exception e) {
				System.out.println("關閉Session發生問題!");
			}
		}
		return sb.toString();
	}
	
	public void finish() {
		try {
			if(connection != null) {
				connection.close();
				connection = null;
			}
		} catch (Exception e) {
			System.out.println("關閉Connection發生問題!");
		}
	}
}
</span>
<span style="font-size:12px;">package com.ilucky.ssh.util;

/**
 * @author IluckySi
 * @date 20140805
 */
public class SshSetting {

	private String ip;
	
	private int port;
	
	private String username;
	
	private String password;

	public String getIp() {
		return ip;
	}

	public void setIp(String ip) {
		this.ip = ip;
	}

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	} 
}
</span>
2.再看測試類:
<span style="font-size:12px;">package com.ilucky.ssh;

import java.util.ArrayList;
import java.util.List;

import com.ilucky.ssh.util.SshSetting;
import com.ilucky.ssh.util.SshUtil;

/**
 * @author IluckySi
 * @date 20140805
 */
public class MainTest {

	public static void main(String[] args) {
	    SshSetting sshSetting = new SshSetting();
	    sshSetting.setIp("192.168.73.246");
	    sshSetting.setPort(22); //ssh預設埠是22.
	    sshSetting.setUsername("root");
	    sshSetting.setPassword("Talent123");
	    SshUtil sshUtil = new SshUtil(sshSetting);
	    List<String> commondList = new ArrayList<String>();
	    commondList.add("cd /home");
	    commondList.add("ls");
	    commondList.add("ls -l");
	    for (int i = 0; i < commondList.size(); i++) {
	    	System.out.println(sshUtil.execute(commondList.get(i)));
	    }
	}
}
/**
執行結果:
cd /home執行成功!

ls執行成功!
anaconda-ks.cfg
install.log
install.log.syslog
tap-home
公共的
模板
視訊
圖片
文件
下載
音樂
桌面

ls -l執行成功!
-rw-r--r--. 1 root root  3233 2月  26 17:29 \
-rw-------. 1 root root  1301 8月  30 2013 anaconda-ks.cfg
-rw-r--r--. 1 root root 39043 8月  30 2013 install.log
-rw-r--r--. 1 root root  9936 8月  30 2013 install.log.syslog
drwxr-xr-x. 2 root root  4096 6月  26 10:08 tap-home
drwxr-xr-x. 2 root root  4096 8月  30 2013 公共的
drwxr-xr-x. 2 root root  4096 8月  30 2013 模板
drwxr-xr-x. 2 root root  4096 8月  30 2013 視訊
drwxr-xr-x. 2 root root  4096 8月  30 2013 圖片
drwxr-xr-x. 2 root root  4096 8月  30 2013 文件
drwxr-xr-x. 2 root root  4096 8月  30 2013 下載
drwxr-xr-x. 2 root root  4096 8月  30 2013 音樂
drwxr-xr-x. 2 root root  4096 12月  5 2013 桌面
*/
</span>

相關推薦

如何通過ssh登入伺服器執行linux指令-ganymed簡單使用()

ganymed是用java實現的一個ssh協議包.通過他可以直接在java程式中連線ssh伺服器並執行指令. 使用步驟如下: 1.建立Connection:   Connection connection = new Connection("192.168.73.246")

[轉]python3之paramiko模組(基於ssh連線進行遠端登入伺服器執行命令和上傳下載檔案的功能)

轉自:https://www.cnblogs.com/zhangxinqi/p/8372774.html 閱讀目錄 1、paramiko模組介紹 2、paramiko的使用方法 回到頂部 1、pa

通過禁止root使用者ssh登入來提高Linux系統的安全性

什麼叫公網,就是公家的網路。一旦把伺服器放到公網上並開啟SSH來協助維護管理之後,你會發現從系統的syslog日誌中看到有來自全球各地的“好友”嘗試登入你的IP。也許你通過加強root使用者的密碼複雜度來提高系統的安全性,一旦想著不停的有人嘗試暴力破解你的系統,相信作為系統管理員的你,肯定是睡不著覺

Java中通過jsch來連線遠端伺服器執行linux命令

有時候你可能需要通過程式碼來控制執行linux命令實現某些功能。 針對這類問題可以使用JSCH來實現,具體程式碼如下: public class CogradientImgFileManager{ private static final Logg

通過ssh遠程執行命令導入定時任務報錯----解決過程

linux ssh su 今天在服務器中通過ssh遠程執行批量導入定時任務時發生了一個問題:總結如下,遠程服務器已設置好ssh秘鑰登錄,登錄用戶為普通用戶,但已設置好擁有免密sudo權限ssh 1.1.1.1 "sudo su -c "echo ‘30 5 * * 5 /bin/sh /root/

通過 ssh 登入到手機 Termux

通過ssh登入到手機 Termux 測試環境 電腦: macOS Mojave 手機: Huawei Mate10Pro Termux是Android上的一個非常強大的終端模擬器。 強大之處在於支援使用apt安裝zsh、git、vim、python、ruby、nodejs、openssh、gcc、gola

java實現 連線遠端伺服器 執行Linux命令 並獲取 執行返回的結果

情景:要通過java連線伺服器,並執行指令碼命令 得到 返回的結果 package com.ideal.openapi.util; import com.jcraft.jsch.*; import org.slf4j.Logger; import org.slf4j.LoggerFacto

如何讓PHP通過ROOT許可權來執行LINUX命令

一般 PHP 在 LINUX 伺服器上執行 shell 命令時,只能擁有 www:www 賬戶許可權,想執行一些系統命令是沒有許可權的,如重啟 apache,因為控制 apache 需要 root 許可權,因此下面的辦法可以讓 PHP 執行 ROOT 許可權的命令。 1

SSH 登入伺服器 提供證書登入

Mac 環境下面-------- 遠端主機ip:HostIpAddress 如果沒有 key 話需要自己生成,或找同事索取. 1.生成key 如果本地有id_rsa和id_rsa.pub這兩個檔案就不要再生成一次了,否則之前已經設定好的網站就白弄了。 ssh-keygen&nbs

用secureCRT通過SSH連線你的Linux(本文基於Ubuntu 10.04)

相信現在有很多學習或者工作需要使用或者是用VPS主機的Linux的人吧..單純的工作學習可以直接硬碟上安裝一個比較適合的Linux系統,但是我們大多時候可能還是需要工作在Windows的平臺下(很多情況也是無奈啊),所以虛擬機器就成了我們使用Linux的最佳選擇。 這是又出

git使用者限制ssh登入伺服器

伺服器額外的防範措施: 搭建git伺服器後通常會建立一個git賬戶,其它人共用這個賬戶來克隆或推送資料到git倉庫中,通常也只需要這個功能,但是如果不加限制,那麼其它人可以通過這個git賬戶登入到主機,那麼這樣是不安全的,所以需要加以限制,方法如下: 編輯/etc/pa

Ubuntu 14.04 LTS ssh登入伺服器免輸密碼(公鑰-私鑰)

Client端 生成公鑰和金鑰 ssh-keygen SSH 金鑰預設儲存在賬戶的家目錄下的 ~/.ssh 目錄中 關鍵是看有沒有用 xxx_rsa 和 xxx_rsa.pub 來命名的一對檔案

Java _ Java 執行Linux 指令

核心程式碼: Process process = Runtime.getRuntime().exec(cmd); InputStreamReader ir = new Inp

jmeter實現本地控制端通過分散式遠端伺服器Linux)併發效能測試

一、背景: 之前在Jmeter外掛監控伺服器效能一篇中說到,在非GUI環境中監控時為了儲存監控資料需要修改jmeter指令碼,並且每次通過施壓機(遠端伺服器,非GUI環境)來壓測時都要將jmeter指令碼上傳然後在伺服器上通過命令列啟動,測試完成後再把結果資料下載到

在Windows中借Telnet或SSH登入路由器的Linux終端並刷寫路由器韌體

一、Windows下利用Telnet協議登入路由器的Linux系統終端 (以DD-WRT韌體的路由器為例。) 1.Telnet是Windows 7已配備的功能,只是預設是沒有開啟,進入:開始-控制面板-程式-開啟或關閉Windows功能; 2.勾選“Telnet伺服器”、

Windows環境下通過SSH登入新浪雲

在後端系統開發中,開發完成之後,如果需要對外提供服務,需要部署到相應的對外公網伺服器上。而作為個人開發者,或者測試使用者,可以選用現在比較成熟的雲,將程式碼託管,著名的有阿里雲(需要備案),本文為了方便說明,我選擇了新浪雲,文件配置地址如下。 Window

自動scp然後ssh登入執行遠端命令

#!/usr/bin/expect set password 123456 set host 191.168.4.249 set command "rmmod pcie_loader.ko &

Mac 解決SSH登入伺服器終端亂碼

Mac 解決SSH登入伺服器終端亂碼 用 Mac OS X 自帶的 SSH 登陸 Linux 後出現中文亂碼,如何解決? 我自己的

利用JSch遠端登入linux伺服器執行指令

最近導師專案,需要搞一個web server,需要在瀏覽器端控制底層虛擬機器部署應用。於是有兩個想法。 一、虛擬機器的映象已經部署好所有的應用,這個專案下,使用者需要的應用是固定的,就那麼幾種,所以可

iOS實現通過SSH2協議連結Linux伺服器,並執行相關指令

使用方法: SSHWrapper* sshWrapper = [[SSHWrapper alloc] init]; NSError* error; [sshWrapper connectToHost:@"0.0.0.0" port:22 user:@"r