/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package demo;
import java.io.IOException;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
/*
@author: Liu Yuanyuan
purpose: test connecting remote computer and execute linux command
*/
public class linux {
public static void main(String[] args) {
String hostname = "194.168.7.61";
String username = "root";
String password = "root";
//指明連接主機的IP地址
Connection conn = new Connection(hostname);
Session ssh = null;
try {
//連接到主機
conn.connect();
//使用用戶名和密碼校驗
boolean isconn = conn.authenticateWithPassword(username, password);
if (!isconn)
{
System.out.println("用戶名稱或者是密碼不正確");
}
else
{
System.out.println("已經連接OK");
ssh = conn.openSession();
ssh.execCommand("su - oracle;sqlplus /nolog");
//ssh.execCommand("perl /root/hello.pl");
//只允許使用一行命令,即ssh物件只能使用一次execCommand這個方法,
//多次使用則會出現例外
//使用多個命令用分號隔開
//ssh.execCommand("cd /root; sh hello.sh");
//將Terminal螢屏上的文字全部列印出來
InputStream is = new StreamGobbler(ssh.getStdout());
BufferedReader brs = new BufferedReader(new InputStreamReader(is));
while (true)
{
String line = brs.readLine();
if (line == null)
{
break;
}
System.out.println(line);
}
}
} catch (IOException e)
{
e.printStackTrace();
} finally
{
//連接的Session和Connection物件都需要關閉
ssh.close();
conn.close();
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/64694.html
標籤:Java相關
