import java.io.BufferedReader; import java.io.FileWriter; import java.io.InputStream; import java.io.InputStreamReader;
import ch.ethz.ssh2.Connection; import ch.ethz.ssh2.Session; import ch.ethz.ssh2.StreamGobbler;
/* * 远程调用linux下的vmstat命令,并将结果完整写入文件中 */ public class SSHTest { /** * @param args * @throws IOException */ /* * 主机地址、端口、用户名、密码 */ static String hostName = "172.16.3.9"; static int port = 2222; static String userName = "root"; static String pwd = "kedats"; public static void main(String[] args) throws Exception { // TODO Auto-generated method stub System.out.println("开始连接主机"); Connection conn = new Connection(hostName, port); conn.connect(); boolean isdenglu = conn.authenticateWithPassword(userName, pwd); if (isdenglu) { System.out.println("ssh2登陆成功"); } else { System.out.println("登陆失败"); } //System.out.println("当前目录:"); Session ses = conn.openSession(); ses.execCommand("vmstat 2"); InputStream stdout = new StreamGobbler(ses.getStdout()); BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
FileWriter fw = new FileWriter("F:\\vmstat.txt"); while (true) { String line = br.readLine(); if (line == null) break; System.out.println(line); fw.write(line+"\r\n",0,line.length()+2); fw.flush();
// OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("data2.txt")); // osw.write(line,0,line.length()); // osw.flush(); // PrintWriter pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream("hello3.txt")),true); // pw.println(line); } System.out.println("运行结果:"+ses.getExitStatus()); //关闭文件 fw.close(); ses.close(); conn.close(); }
} |