zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Java利用SSH登录Linux执行命令工具类详解程序员

JAVALinuxssh工具程序员 详解 利用 登录
2023-06-13 09:20:05 时间
public static int execute(String username, String ip, int port, String password, String command) log.info("进入ShellUtils工具类的execute方法"); int returnCode = 0; JSch jsch = new JSch(); MyUserInfo userInfo = new MyUserInfo(); List String stdout = new ArrayList (); try //创建session并且打开连接,因为创建session之后要主动打开连接 log.info("创建session并且打开连接"); Session session = jsch.getSession(username, ip, port); session.setPassword(password); //此处必须设置userInfo session.setUserInfo(userInfo); session.connect(); //打开通道,设置通道类型,和执行的命令 log.info("打开通道、执行的命令,command = " + command); Channel channel = session.openChannel("exec"); ChannelExec channelExec = (ChannelExec)channel; channelExec.setCommand(command); channelExec.setInputStream(null); BufferedReader input = new BufferedReader(new InputStreamReader(channelExec.getInputStream())); channelExec.connect(); //接收远程服务器执行命令的结果 String line; while ((line = input.readLine()) != null) stdout.add(line); input.close(); //关闭通道 channelExec.disconnect(); //关闭session session.disconnect(); log.info("执行命令返回 :" + stdout.toString()); catch (Exception e) log.error("ShellUtils工具类的execute方法执行异常", e); returnCode = 1; e.printStackTrace(); return returnCode; }
 

import com.jcraft.jsch.UserInfo; 

public class MyUserInfo implements UserInfo { 

 @Override 

 public String getPassphrase() { 

 // TODO Auto-generated method stub 

 System.out.println("MyUserInfo.getPassphrase()"); 

 return null; 

 @Override 

 public String getPassword() { 

 // TODO Auto-generated method stub 

 System.out.println("MyUserInfo.getPassword()"); 

 return null; 

 @Override 

 public boolean promptPassphrase(String arg0) { 

 // TODO Auto-generated method stub 

 System.out.println("MyUserInfo.promptPassphrase()"); 

 System.out.println(arg0); 

 return false; 

 @Override 

 public boolean promptPassword(String arg0) { 

 // TODO Auto-generated method stub 

 System.out.println("MyUserInfo.promptPassword()"); 

 System.out.println(arg0); 

 return false; 

 @Override 

 public boolean promptYesNo(String arg0) { 

 // TODO Auto-generated method stub 

 System.out.println("MyUserInfo.promptYesNo()"); 

 System.out.println(arg0); 

 if (arg0.contains("The authenticity of host")) { 

 return true; 

 return true; 

 @Override 

 public void showMessage(String arg0) { 

 // TODO Auto-generated method stub 

 System.out.println("MyUserInfo.showMessage()"); 

}

原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/2927.html

服务器部署程序员系统优化网站设置运维