JAVA shell export_Java 远程调用Shell
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:
我來說兩句
顯示全部
內容
昵稱
驗證
提交評論
總結
以上是生活随笔為你收集整理的JAVA shell export_Java 远程调用Shell的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 电脑怎么打出冒号符号_Mac小技巧:教你
- 下一篇: linux 终端显示白底,mac终端使用