JAVA shell export_Java 远程调用Shell
Java 遠(yuǎn)程調(diào)用Shell
上一篇 /
下一篇 ?2014-01-21 13:29:22
/ 個(gè)人分類(lèi):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:
我來(lái)說(shuō)兩句
顯示全部
內(nèi)容
昵稱(chēng)
驗(yàn)證
提交評(píng)論
總結(jié)
以上是生活随笔為你收集整理的JAVA shell export_Java 远程调用Shell的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 电脑怎么打出冒号符号_Mac小技巧:教你
- 下一篇: java compare equla_J