java如何本地执行远程sh命令,以及跳过 Kerberos的认证输入方法
1、这是执行shell脚本的代码块
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
public class SSHUtils {
/**
* 远程 执行命令并返回结果调用过程 是同步的(执行完才会返回)
* @param host 主机名
* @param user 用户名
* @param psw 密码
* @param port 端口
* @param command 命令
* @return
*/
public static String exec(String host,String user,String psw,int port,String command){
long startTime=System.currentTimeMillis();
StringBuffer sb= new StringBuffer();
Session session =null;
ChannelExec openChannel =null;
try {
JSch jsch=new JSch();
session = jsch.getSession(user, host, port);
java.util.Properties config = new java.util.Properties();
//添加此行用于过滤掉Kerberos认证
config.put("PreferredAuthentications","publickey,keyboard-interactive,password");
config.put("StrictHostKeyChecking", "no");//跳过公钥的询问
session.setConfig(config);
session.setPassword(psw);
session.connect(2000);//设置连接的超时时间
openChannel = (ChannelExec) session.openChannel("exec");
openChannel.setCommand(command); //执行命令
int exitStatus = openChannel.getExitStatus(); //退出状态为-1,直到通道关闭
System.out.println(exitStatus);
// 下面是得到输出的内容
openChannel.connect();
InputStream in = openChannel.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String buf = null;
while ((buf = reader.readLine()) != null) {
sb.append(buf+"\n");
}
} catch (Exception e) {
e.printStackTrace();
sb.append(e.getMessage()+"\n");
}finally{
if(openChannel!=null&&!openChannel.isClosed()){
openChannel.disconnect();
}
if(session!=null&&session.isConnected()){
session.disconnect();
}
}
long endTime= System.currentTimeMillis();
System.out.println("消耗时间(ms):"+(endTime-startTime));
System.out.println(sb.toString());
return sb.toString();
}
public static void main(String[] args) {
exec("10.19.248.28","root","Bocom_123",22,"sh /a/start.sh");
}
}
2、执行结果如下: