JAVA实现SSH远程登录linux机器,并执行相关命令

这一生的挚爱 提交于 2020-01-22 07:51:55

1、SSH登录及执行命令

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Vector;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.Session;

public class sshForLinux {
	public static Vector<String> exeCommand(String host, int port, String user, String password, String shell)
			throws Exception {
		Vector<String> stdout = new Vector<String>();
		JSch jsch = new JSch();
		Session session = jsch.getSession(user, host, port);
		if (session == null) {
	        throw new Exception("session is null");
	    }
		session.setPassword(password);
		session.setConfig("StrictHostKeyChecking", "no");
		try{
			session.connect(30000);
		}catch (Exception e) {
	        throw new Exception("Invalid connection to remote port or wrong username and password!!!"+host+","+user+","+password);
	    }
		
		Channel channel = session.openChannel("exec");
		((ChannelExec) channel).setCommand(shell);

		channel.setInputStream(null);
		BufferedReader input = new BufferedReader(new InputStreamReader(channel.getInputStream()));

		channel.connect();
		System.out.println("The remote shell is: " + shell);

		String line;
		while ((line = input.readLine()) != null) {
			stdout.add(line);
		}
		input.close();

		channel.disconnect();
		session.disconnect();

		return stdout;
	}
}

2、实例(获取某文件夹下文件最后修改时间)

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!