本文整理汇总了Java中ch.ethz.ssh2.StreamGobbler类的典型用法代码示例。如果您正苦于以下问题:Java StreamGobbler类的具体用法?Java StreamGobbler怎么用?Java StreamGobbler使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
StreamGobbler类属于ch.ethz.ssh2包,在下文中一共展示了StreamGobbler类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: startTest
import ch.ethz.ssh2.StreamGobbler; //导入依赖的package包/类
@Override
public void startTest(){
Session session=null;
try {
getConnection();
if(connection==null)
throw new IOException("Unable to connect the server!");
session = connection.openSession();
session.execCommand(shellofstartTest);
System.out.println("Here is some information about the remote host:");
InputStream stderr = new StreamGobbler(session.getStderr());
BufferedReader br = new BufferedReader(new InputStreamReader(stderr));
InputStream stdout = new StreamGobbler(session.getStdout());
BufferedReader stdbr = new BufferedReader(new InputStreamReader(stdout));
System.out.println("Test had been started successfully!");
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}finally{
if(session != null)
session.close();
closeConnection();
}
}
示例2: main
import ch.ethz.ssh2.StreamGobbler; //导入依赖的package包/类
public static void main(String[] args) throws IOException {
ControlStream cs = new SSHControlStream(args[0], args[1]);
cs.startProgram(args[2]);
/* read stdout */
InputStream stdout = new StreamGobbler(cs.getProgramStdOut());
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:" + cs.getExitCode());
cs.close();
}
示例3: main
import ch.ethz.ssh2.StreamGobbler; //导入依赖的package包/类
public static void main(String[] args) throws IOException {
ControlStream cs = new GSISSHControlStream(args[0], args[1]);
cs.startProgram(args[2]);
/* read stdout */
InputStream stdout = new StreamGobbler(cs.getProgramStdOut());
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:" + cs.getExitCode());
cs.close();
}
示例4: getMillisecondSpentForCPU
import ch.ethz.ssh2.StreamGobbler; //导入依赖的package包/类
public long getMillisecondSpentForCPU() {
try {
sess = conn.openSession();
// get millisecond spent in IO from beginning of time for disk
// diskname
sess.execCommand("cat /proc/stat | grep \"cpu \"| awk '{ print $5}' ");
InputStream stdout = new StreamGobbler(sess.getStdout());
BufferedReader br = new BufferedReader(
new InputStreamReader(stdout));
String line = br.readLine();
sess.close();
if (line != null)
return Long.parseLong(line);
} catch (Exception e) {
e.printStackTrace(System.err);
}
return -1;
}
示例5: getMillisecondSpentForSDAIO
import ch.ethz.ssh2.StreamGobbler; //导入依赖的package包/类
public long getMillisecondSpentForSDAIO() {
try {
sess = conn.openSession();
// get millisecond spent in IO from beginning of time for disk
// diskname
sess.execCommand("cat /proc/diskstats | grep \"" + diskname
+ " \" | awk '{ print $13}' ");
InputStream stdout = new StreamGobbler(sess.getStdout());
BufferedReader br = new BufferedReader(
new InputStreamReader(stdout));
String line = br.readLine();
sess.close();
if (line != null)
return Integer.parseInt(line);
} catch (Exception e) {
e.printStackTrace(System.err);
}
return -1;
}
示例6: SSHClient
import ch.ethz.ssh2.StreamGobbler; //导入依赖的package包/类
public static String SSHClient(String command,SSHComm obj) throws IOException{
System.out.println("inside the ssh function");
String res="";
try
{
sess.execCommand(command);
InputStream stdout = new StreamGobbler(sess.getStdout());
BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
System.out.println("the output of the command is");
while (true)
{
String line = br.readLine();
res=res+line+"\n";
if (line == null)
break;
System.out.println(line);
}
System.out.println("ExitCode: " + sess.getExitStatus());
}
catch (IOException e)
{
e.printStackTrace(System.err);
}
obj=new SSHComm();
return res;
}
示例7: getDiskStats
import ch.ethz.ssh2.StreamGobbler; //导入依赖的package包/类
public long[] getDiskStats() {
long[] diskstats = new long[11];
try {
sess = conn.openSession();
// get millisecond spent in IO from beginning of time for disk
// diskname
sess.execCommand("cat /proc/diskstats | grep \"" + diskname + " \"");
InputStream stdout = new StreamGobbler(sess.getStdout());
BufferedReader br = new BufferedReader(
new InputStreamReader(stdout));
String line = br.readLine();
StringTokenizer st = new StringTokenizer(line);
st.nextToken();
st.nextToken();
st.nextToken();
for (int i = 0; i < 11; i++) {
if (st.hasMoreTokens()) {
diskstats[i] = Long.parseLong(st.nextToken());
}
}
sess.close();
return diskstats;
} catch (Exception e) {
e.printStackTrace(System.err);
}
return null;
}
示例8: exec
import ch.ethz.ssh2.StreamGobbler; //导入依赖的package包/类
public void exec(String command)
throws IOException{
// Sending command to server
if (verboseMode == true){
consoleStream.println(
"Executing" +
" " +
"'" +
command +
"'" +
".");
}
Session session = connection.openSession();
session.execCommand(command);
// Copying server stdout on local stdout
InputStream remoteStdout =
new StreamGobbler(session.getStdout());
BufferedReader remoteStdoutReader =
new BufferedReader(new InputStreamReader(remoteStdout));
String line;
while ((line = remoteStdoutReader.readLine()) != null){
consoleStream.println(line);
}
// Close session
session.close();
}
示例9: exeRemoteConsole
import ch.ethz.ssh2.StreamGobbler; //导入依赖的package包/类
public static List<String> exeRemoteConsole(String hostname, String username, String password, String cmd) {
List<String> result = new ArrayList<String>();
//指明连接主机的IP地址
Connection conn = new Connection(hostname);
Session ssh = null;
try {
//连接到主机
conn.connect();
//使用用户名和密码校验
boolean isconn = conn.authenticateWithPassword(username, password);
if (!isconn) {
logger.error("用户名称或者是密码不正确");
} else {
logger.info("已经连接OK");
ssh = conn.openSession();
//使用多个命令用分号隔开
// ssh.execCommand("pwd;cd /tmp;mkdir shb;ls;ps -ef|grep weblogic");
ssh.execCommand(cmd);
//只允许使用一行命令,即ssh对象只能使用一次execCommand这个方法,多次使用则会出现异常
// ssh.execCommand("mkdir hb");
//将屏幕上的文字全部打印出来
InputStream is = new StreamGobbler(ssh.getStdout());
BufferedReader brs = new BufferedReader(new InputStreamReader(is));
for (String line = brs.readLine(); line != null; line = brs.readLine()) {
result.add(line);
}
}
//连接的Session和Connection对象都需要关闭
if (ssh != null) {
ssh.close();
}
conn.close();
} catch (IOException e) {
logger.error("", e);
}
return result;
}
示例10: exportDataBase
import ch.ethz.ssh2.StreamGobbler; //导入依赖的package包/类
/**
* export database;
*/
public void exportDataBase() {
logger.info("start backup database");
String username = Config.getProperty("jdbc.username_dev");
String password = Config.getProperty("jdbc.password_dev");
String database = Config.getProperty("jdbc.database");
String host = Config.getProperty("jdbc.host_dev");
String os = System.getProperty("os.name");
String file_path = null;
// if (os.toLowerCase().startsWith("win")) { //根据系统类型
// file_path = System.getProperty("user.dir") + "\\sql\\";
// } else {
// file_path = System.getProperty("user.dir") + "/sql/";//保存的路径
// }
file_path = System.getProperty("myblog.path") + "sql";
String file_name = "/myblog" + DateTime.now().toString("yyyyMMddHHmmss") + ".sql";
String file = file_path + file_name;
logger.info("file_path and file_name: " + file);
//server
String s_host = Config.getProperty("server.host");
Integer s_port = Config.getIntProperty("server.port");
String s_username = Config.getProperty("server.username");
String s_password = Config.getProperty("server.password");
try {
StringBuffer sb = new StringBuffer();
sb.append("mysqldump -u " + username + " -p" + password + " -h " + host + " " +
database + " >" + file);
String sql = sb.toString();
logger.info(sql);
//connect to server
Connection connection = new Connection(s_host, s_port);
connection.connect();
boolean isAuth = connection.authenticateWithPassword(s_username, s_password);
if (!isAuth) {
logger.error("server login error");
}
Session session = connection.openSession();
session.execCommand(sql);
InputStream stdout = new StreamGobbler(session.getStdout());
BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
while (true) {
String line = br.readLine();
if (line == null)
break;
System.out.println(line);
}
session.close();
connection.close();
stdout.close();
br.close();
logger.info("backup finish");
logger.info(sb.toString());
} catch (Exception e) {
logger.error("error", e);
}
}
示例11: doCommond
import ch.ethz.ssh2.StreamGobbler; //导入依赖的package包/类
/**
* 远程执行命令
* @param ip
* @param user
* @param pwd
* @param cmd
* @return
*/
public static String doCommond(Connection conn,String cmd){
String result = "";
try {
if(conn==null){
System.out.println("请先链接服务器");
}else{
Session sess = conn.openSession();
sess.execCommand(cmd);
InputStream stdout = new StreamGobbler(sess.getStdout());
BufferedReader stdoutReader = new BufferedReader(new InputStreamReader(stdout));
while(true){
String line = stdoutReader.readLine();
if (line == null)
break;
result+=line+StaticKeys.SPLIT_BR;
}
//连接的Session和Connection对象都需要关闭
stdoutReader.close();
sess.close();
}
} catch (IOException e) {
System.out.println("执行linux命令错误:"+e.toString());
}
if(result.endsWith(StaticKeys.SPLIT_BR)){
result = result.substring(0, result.length()-StaticKeys.SPLIT_BR.length());
}
if(!StringUtils.isEmpty(result)){
if(cmd.contains("DEV")||cmd.contains("iostat")){
if(result.contains("</br></br>")){
result = result.substring(result.lastIndexOf("</br></br>")+10);
}
}
if(cmd.contains("mpstat")){
if(result.contains("</br></br>")){
result = result.substring(result.lastIndexOf("</br></br>")+10);
int s = result.indexOf("</br>")+5;
s = result.indexOf("</br>",s);
result = result.substring(0,s);
}
}
}
return result;
}
示例12: executeCommand
import ch.ethz.ssh2.StreamGobbler; //导入依赖的package包/类
private boolean executeCommand(String command) throws IOException {
/*
* Create temp file so we can use exec command Not ideal, but best I
* could come up with for now Uses underlying system commands, not
* relying on external libraries this way. File will be deleted at end
* of execution. In the case of program error, will also be removed upon
* JVM termination (if it still persists).
*/
File tempBashCmd = File.createTempFile("tmp", ".sh", new File("/tmp"));
FileWriter bashFile = new FileWriter(tempBashCmd);
tempBashCmd.setExecutable(true);
tempBashCmd.deleteOnExit();
/*
* Write out expect command to tmp shell script (if using password authentication
*/
bashFile.write("#!/bin/bash");
bashFile.write("\n");
bashFile.write("export SSHPASS='"+config.getSshPass()+"'");
bashFile.write("\n\n");
bashFile.write(command);
bashFile.write("\n");
bashFile.close();
Runtime rt = Runtime.getRuntime();
Process proc = null;
try {
// Using underlying 'sh' command to pass password for rsync
proc = rt.exec("sh " + tempBashCmd.getAbsolutePath());
// Use StreamGobbler to for err/stdout to prevent blocking
InputStream stdout = new StreamGobbler(proc.getInputStream());
InputStream stderr = new StreamGobbler(proc.getErrorStream());
OutputStream stdin = proc.getOutputStream();
InputStreamReader isrErr = new InputStreamReader(stderr);
BufferedReader brErr = new BufferedReader(isrErr);
// Print output to stdout
String val = null;
InputStreamReader isrStd = new InputStreamReader(stdout);
BufferedReader brStd = new BufferedReader(isrStd);
int lineCount = 0;
while ((val = brStd.readLine()) != null) {
// Print out loading animation
if(lineCount % 5 == 0) System.out.print("*** -- ***\r");
else if(lineCount % 5 == 1) System.out.print("*** \\ ***\r");
else if(lineCount % 5 == 2) System.out.print("*** | ***\r");
else if(lineCount % 5 == 3) System.out.print("*** / ***\r");
else if(lineCount % 5 == 4) System.out.print("*** -- ***\r");
lineCount++;
}
// Clean up the loading animation line
System.out.print(" \r");
// Print errors stdout so user knows what went wrong
while ((val = brErr.readLine()) != null) {
if(!val.contains("stdin: is not a tty"))
System.err.println(Extras.ANSI_RED + ">>[Error]: " + val + Extras.ANSI_RESET);
}
int exitVal = proc.waitFor();
if (exitVal != 0) {
System.out.println(Extras.ANSI_YELLOW
+ ">>[Warning]: There might have been a problem executing the command. Please double check everything worked as expected."
+ Extras.ANSI_RESET);
}
// Clean up
brStd.close();
brErr.close();
stdin.close();
} catch (Exception e) {
e.printStackTrace();
}
// Remove the file, print completion message
boolean deleteStatus = tempBashCmd.delete();
return( deleteStatus );
}
示例13: importRemoteDbBackup
import ch.ethz.ssh2.StreamGobbler; //导入依赖的package包/类
private void importRemoteDbBackup(File file) {
String[] command = { "/bin/sh", "-c",
cr.getMysqlPath() + "mysql --user=" + localConfig.getDbUser() + " --password="
+ localConfig.getDbPass().replace("'", "\'") + " --port=" + localConfig.getDbPort() + " --database="
+ localConfig.getDatabase() + " < " + file.getAbsolutePath() };
System.out.println(Extras.ANSI_GREEN + "\tlocal | " + Extras.ANSI_RESET + Arrays.toString(command));
Runtime rt = Runtime.getRuntime();
Process proc = null;
try {
// Using underlying mysqldump for dba backup
proc = rt.exec(command);
// Use StreamGobbler to for err/stdout to prevent blocking
InputStream stdout = new StreamGobbler(proc.getInputStream());
InputStream stderr = new StreamGobbler(proc.getErrorStream());
OutputStream stdin = proc.getOutputStream();
InputStreamReader isrErr = new InputStreamReader(stderr);
BufferedReader brErr = new BufferedReader(isrErr);
// Print status to stdout
String val = null;
InputStreamReader isrStd = new InputStreamReader(stdout);
BufferedReader brStd = new BufferedReader(isrStd);
int lineCount = 0;
while ((val = brStd.readLine()) != null) {
// Print out loading animation
if(lineCount % 5 == 0) System.out.print("*** -- ***\r");
else if(lineCount % 5 == 1) System.out.print("*** \\ ***\r");
else if(lineCount % 5 == 2) System.out.print("*** | ***\r");
else if(lineCount % 5 == 3) System.out.print("*** / ***\r");
else if(lineCount % 5 == 4) System.out.print("*** -- ***\r");
lineCount++;
}
// Print errors stdout so user knows what went wrong
while ((val = brErr.readLine()) != null) {
System.err.println(Extras.ANSI_RED + ">> [Error]: " + val + Extras.ANSI_RESET);
}
int exitVal = proc.waitFor();
// Clean up the loading animation line
System.out.print(" \r");
if (exitVal != 0) {
System.out.println(Extras.ANSI_YELLOW
+ ">>[Warning]: There might have been a problem executing the command. Please double check everything worked as expected."
+ Extras.ANSI_RESET);
}
// Clean up
brStd.close();
brErr.close();
stdin.close();
} catch (Exception e) {
e.printStackTrace();
}
}
示例14: main
import ch.ethz.ssh2.StreamGobbler; //导入依赖的package包/类
public static void main(String[] args)
{
String hostname = "127.0.0.1";
String username = "joe";
String password = "joespass";
try
{
/* Create a connection instance */
Connection conn = new Connection(hostname);
/* Now connect */
conn.connect();
/* Authenticate.
* If you get an IOException saying something like
* "Authentication method password not supported by the server at this stage."
* then please check the FAQ.
*/
boolean isAuthenticated = conn.authenticateWithPassword(username, password);
if (isAuthenticated == false)
throw new IOException("Authentication failed.");
/* Create a session */
Session sess = conn.openSession();
sess.execCommand("uname -a && date && uptime && who");
System.out.println("Here is some information about the remote host:");
/*
* This basic example does not handle stderr, which is sometimes dangerous
* (please read the FAQ).
*/
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);
}
/* Show exit status, if available (otherwise "null") */
System.out.println("ExitCode: " + sess.getExitStatus());
/* Close this session */
sess.close();
/* Close the connection */
conn.close();
}
catch (IOException e)
{
e.printStackTrace(System.err);
System.exit(2);
}
}
示例15: main
import ch.ethz.ssh2.StreamGobbler; //导入依赖的package包/类
public static void main(String[] args)
{
String hostname = "my-ssh-server";
String username = "joe";
String password = "joespass";
String proxyHost = "192.168.1.1";
int proxyPort = 3128; // default port used by squid
try
{
/* Create a connection instance */
Connection conn = new Connection(hostname);
/* We want to connect through a HTTP proxy */
conn.setProxyData(new HTTPProxyData(proxyHost, proxyPort));
// if the proxy requires basic authentication:
// conn.setProxyData(new HTTPProxyData(proxyHost, proxyPort, "username", "secret"));
/* Now connect (through the proxy) */
conn.connect();
/* Authenticate.
* If you get an IOException saying something like
* "Authentication method password not supported by the server at this stage."
* then please check the FAQ.
*/
boolean isAuthenticated = conn.authenticateWithPassword(username, password);
if (isAuthenticated == false)
throw new IOException("Authentication failed.");
/* Create a session */
Session sess = conn.openSession();
sess.execCommand("uname -a && date && uptime && who");
System.out.println("Here is some information about the remote host:");
/*
* This basic example does not handle stderr, which is sometimes dangerous
* (please read the FAQ).
*/
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);
}
/* Show exit status, if available (otherwise "null") */
System.out.println("ExitCode: " + sess.getExitStatus());
/* Close this session */
sess.close();
/* Close the connection */
conn.close();
}
catch (IOException e)
{
e.printStackTrace(System.err);
System.exit(2);
}
}