Java 远程调用Shell
上一篇 /
下一篇 2014-01-21 13:29:22
/ 个人分类:Java
Remote Shell Scripts need to export the ENV variable again.
public class JavaRemoteRunShell {
private Connection conn;
private String ipAddr;
private String charset = Charset.defaultCharset().toString();
private String userName;
private String password;
public JavaRemoteRunShell(String ipAddr, String userName, String password, String charset) {
this.ipAddr = ipAddr;
this.userName = userName;
this.password = password;
if(charset != null) {
this.charset = charset;
}
}
public boolean login() throws IOException {
conn = new Connection(ipAddr);
conn.connect(); //
return conn.authenticateWithPassword(userName, password); //
}
public String exec(String cmds) {
InputStream in = null;
String result = "";
try {
if (this.login()) {
Session session = conn.openSession(); // open one session
session.execCommand(cmds);
in = session.getStdout();
result = this.processStdout(in, this.charset);
System.out.println(result);
System.out.println("ExitCode: " + session.getExitStatus());
session.close();
conn.close();
}
} catch (IOException e1) {
e1.printStackTrace();
}
return result;
}
public String processStdout(InputStream in, String charset) {
byte[] buf = new byte[1024];
StringBuffer sb = new StringBuffer();
try {
while (in.read(buf) != -1) {
sb.append(new String(buf, charset));
}
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
public static void lsViaSSH(String hostname, String username, String password) throws Exception {
Connection conn = new Connection(hostname);
conn.connect();
boolean isAuthenticated = conn.authenticateWithPassword(username, password);
System.out.println(isAuthenticated);
if (isAuthenticated = true){
Session sess = conn.openSession();
sess.execCommand("sh test.sh " );
InputStream stdout = new StreamGobbler(sess.getStdout());
BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
sess.close();
conn.close();
}
}
public static void main(String[] args ) throws Exception{
String ipAddr = "127.0.0.1";
String userName = "test";
String password = "password";
String charset = Charset.defaultCharset().toString();
JavaRemoteRunShell c = new JavaRemoteRunShell( ipAddr, userName, password, charset);
c.login();
String cmd1="sh test.sh";
System.out.println(c.exec(cmd1));
}
}
TAG:
我来说两句
显示全部
内容
昵称
验证
提交评论