java实现ssh_Java实现ssh命令登录主机执⾏shell命令importjava.io.BufferedReader;importjava.io.IOException;importjava.io.InputStream;importjava.io.InputStreamReader;importjava.i classSshUtil {private static String DEFAULT_CHAR_SET = "UTF-8";private static String tipStr =
"=======================%s=======================";private static String splitStr =
"=====================================================";/*** 登录主机
*@return* 登录成功返回true,否则返回false*/
public staticConnection login(String ip, String userName, String password){boolean isAuthenticated = false;
Connection conn= null;long startTime =Instance().getTimeInMillis();try{
conn= newConnection(ip);
isAuthenticated= conn.authenticateWithPassword(userName, password); //认证
if(isAuthenticated){
System.out.println(String.format(tipStr,"认证成功"));
}else{
System.out.println(String.format(tipStr,"认证失败"));
}
}catch(IOException e) {
e.printStackTrace();
}long endTime =Instance().getTimeInMillis();
System.out.println("登录⽤时: " + (endTime - startTime)/1000.0 + "s\n" +splitStr);returnconn;
}/*** 远程执⾏shell脚本或者命令
*@paramcmd
* 即将执⾏的命令
*@return* 命令执⾏完后返回的结果值*/
public staticString execute(Connection conn, String cmd){
String result= "";
Session session= null;try{if(conn != null){
session= conn.openSession(); //打开⼀个会话
result =Stdout(), DEFAULT_CHAR_SET);//如果为得到标准输出为空,说明脚本执⾏出错了
if(StringUtils.isBlank(result)){
result=Stderr(), DEFAULT_CHAR_SET);
}else{
System.out.println("【执⾏命令成功】\n执⾏的命令如下:\n" +cmd);
}
}
}catch(IOException e) {
e.printStackTrace();
}finally{if (conn != null) {
conn.close();
}if (session != null) {
session.close();
}
}returnresult;
}/*** 解析脚本执⾏返回的结果集
*@paramin 输⼊流对象
*@paramcharset 编码
*@return* 以纯⽂本的格式返回*/
private staticString processStdout(InputStream in, String charset){
InputStream stdout= newStreamGobbler(in);
StringBuffer buffer= newStringBuffer();try{
BufferedReader br= new BufferedReader(newInputStreamReader(stdout, charset)); String line= null;while((line = br.readLine()) != null){
buffer.append(line+ "\n");
}
}catch(UnsupportedEncodingException e) {
e.printStackTrace();
}catch(IOException e) {
e.printStackTrace();
}String();
}public static voidmain(String[] args){
String ip= "192.168.123.234"; //此处根据实际情况,换成⾃⼰需要访问的主机IP
String userName = "root";
String password= "password";
Connection conn=SshUtil.login(ip, userName, password);
String cmd= "cd /home/miracle&&pwd&&ls&&";
String ute(conn, cmd);
System.out.println(splitStr+ "\n执⾏的结果如下: \n" + result +splitStr); }
shell脚本返回执行结果}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。