|
|
茫茫網海中的冷日
發生過的事,不可能遺忘,只是想不起來而已! |
|
恭喜您是本站第 1735126
位訪客!
登入 | 註冊
|
|
|
|
發表者 |
討論內容 |
冷日 (冷日) |
發表時間:2018/2/22 7:17 |
- Webmaster

- 註冊日: 2008/2/19
- 來自:
- 發表數: 15773
|
- [分享]冷日 Ganymed SSH-2 Sample Code
- 冷日幾經測試,終於把 Key Base Auth 搞定了!!!
先看看比較簡單的『帳密法』:
static void connect2Server(String hostname, String username, String password) {
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);
}
System.out.println("ExitCode: " + sess.getExitStatus());
sess.close();
conn.close();
} catch (IOException e) {
e.printStackTrace(System.err);
System.exit(2);
}
}
然後,就是 Key Base 囉:
static void PublicKeyAuthentication(String hostname, String username, String keyfilePass) {
File keyfile = new File("C:\\Temp\\keystore\\openssh"); // or "~/.ssh/id_dsa"
System.out.println("Win-Way : Connect SSH Server with Public Key - [" + keyfile.toString() + "]!");
try {
Connection conn = new Connection(hostname);
conn.connect();
boolean isAuthenticated = conn.authenticateWithPublicKey(username, keyfile, keyfilePass);
if (isAuthenticated == false)
throw new IOException("Authentication failed.");
Session sess = conn.openSession();
sess.execCommand("uname -a && date && uptime && who");
InputStream stdout = new StreamGobbler(sess.getStdout());
BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
System.out.println("Here is some information about the remote host:");
while (true) {
String line = br.readLine();
if (line == null)
break;
System.out.println(line);
}
sess.close();
conn.close();
} catch (IOException e) {
e.printStackTrace(System.err);
System.exit(2);
}
}
首先必須紀錄的是,要丟去 Unix Like Server 上的要使用 Public key for pasting into OpenSSH authorized_keys file: 內的資訊! 不能用 puttygen Save 出來的 public key!
另外很重要必須筆記的另一件則是:
keyfile = new File("C:\\Temp\\keystore\\openssh");
也就是 puttygen 產出的 Public 不能直接拿來用!!! 務必要進行 Conversions -> Export OpenSSH Key 後才能用!!!
Ganymed SSH-2 for Java 官網:http://www.ganymed.ethz.ch/ssh2/
|
|
討論串
|