使用jsch连接到linux服务器并进行命令查询磁盘监控情况

版权声明:转载的话 请标明出处 https://blog.csdn.net/qq_28198181/article/details/82789299

因为要写一个磁盘监控程序可以随时的获取到服务器的磁盘空间的占用情况,所以需要连接到服务器上面,第一次接触,所以在网上查找了方法并记个笔记如下:

1.添加依赖jsch

 这个是连接到服务器的一个框架,我用的这个,应该有其他的。

<dependency>
	<groupId>com.jcraft</groupId>
    	<artifactId>jsch</artifactId>
	<version>0.1.53</version>
</dependency>

创建一个mavaen工程,在pom文件中放入以上。保存

BufferedReader reader = null;
Channel channel = null;

在maven-Dependencies中会有对应的jar包

然后创建一个Connection类,准备开始连接服务器

2.实现与服务器的交互

先 new 一个 jsch对象,和Session对象(注意包在com.jcraft.jsch)下

对于session 查询了一下,作用如下:

Session的作用是实现与远端服务器的交互,负责建立TCP连接,发送数据导远端和接收远端发来的数据。
Session与远端建立连接后,会建立一个前台线程,该线程负责接收远端发来的数据,并根据消息类型,执行处理函数。

接下来需要让session得到获取的值,通过jsch对象的getSession方法

扫描二维码关注公众号,回复: 3561151 查看本文章
session = jsch.getSession(user, host, port);
session.setPassword(password);

这里的getSession方法在源代码中是重载过三次的,也就是说有三个方法,如下:
 getSession(String host)  默认端口为22, user 为null
 getSession(String username, String host)  默认 端口为22
 getSession(String username, String host, int port) 全部自己设置

接着设置密码

  session.setPassword(password);

设置一个config,如果设置了无口令 SSH 登录(即通过客户端公钥认证),就可以直接连接到远程主机。这是基于 SSH

如下:

    Properties config = new Properties();
	 // 如果设置了无口令 SSH 登录(即通过客户端公钥认证),就可以直接连接到远程主机。这是基于 SSH
	 // 协议的自动化任务常用的手段。
	config.put("StrictHostKeyChecking", "no");

	session.setConfig(config); // 设置配置文件

最后通过session连接就可以了

session.connect();
System.out.println("连接seesion 成功");

整体源代码如下(host,port user,password是需要自己设置,按个人情况编写):

public class Connection {

	static JSch jsch = new JSch();

	static Session session;
	
	static String host = "127.0.0.1";

	static Integer port = 22;
	
	static String user = "user_1";

	static String password = "test";

	
	static {

		try {
			/**
			 * Session的作用是实现与远端服务器的交互,负责建立TCP连接,发送数据导远端和接收远端发来的数据。
			 * Session与远端建立连接后,会建立一个前台线程,该线程负责接收远端发来的数据,并根据消息类型,执行处理函数
			 */
			
			/*getSession有三个重载
			 * getSession(String host)  默认端口为22 user 为null
			 * getSession(String username, String host)  默认 端口为22
			 * getSession(String username, String host, int port) 全部自己设置
			 */
			session = jsch.getSession(user, host, port);
			session.setPassword(password);
			
			Properties config = new Properties();
			 // 如果设置了无口令 SSH 登录(即通过客户端公钥认证),就可以直接连接到远程主机。这是基于 SSH
			 // 协议的自动化任务常用的手段。
			config.put("StrictHostKeyChecking", "no");

			session.setConfig(config); // 设置配置文件

			
			session.connect();
			System.out.println("连接seesion 成功");

		} catch (JSchException e) {
			e.printStackTrace();
			System.out.println("连接seesion 失败" + e.getMessage());
		}

	}
    
   
 public void getMessage() throws JSchException, IOException {
        ...
    }

 public static void main(String[] args) throws JSchException, IOException {
    ....
    }
}

这样就连接成功了

接下来要如何去访问磁盘监控呢

3.输入命令查询磁盘监控与读取数据(getMessage()方法)

取了BufferedReader流对象和Channel对象(jsch中的channel对象),并且写入了一个命令command

BufferedReader reader = null;
Channel channel = null;
String command = "df -hP";  //查询磁盘监控

接着 使用上面 的session对象获取getChannel()方法的到channel通道,然后将命令放进去,channel去连接执行

//在这里使用命令通道比使用shell通道好,不用处理命令提示符
channel = session.openChannel("exec"); 
((ChannelExec) channel).setCommand(command);
channel.connect();

使用上面的Read流去接取channel获取的数据

InputStream in = channel.getInputStream();
reader = new BufferedReader(new InputStreamReader(in));

读取出来就行了

while ((buf = reader.readLine()) != null) {

       System.out.println(buf);
}

最后关掉Reader流

reader.close();

这个方法的完整代码:

public void getMessage() throws JSchException, IOException {

		System.out.println("SessionUserName:" + session.getUserName());
		System.out.println("SessionUserPort:" + session.getPort());

		// 执行相关命令
		BufferedReader reader = null;
		Channel channel = null;

		if (command != null) {
			System.out.println("开始执行命令行");
			channel = session.openChannel("exec"); //在这里使用命令通道比使用shell通道好,不用处理命令提示符
			((ChannelExec) channel).setCommand(command);
			channel.connect();
			InputStream in = channel.getInputStream();
			reader = new BufferedReader(new InputStreamReader(in));

			String buf = null;
			
			while ((buf = reader.readLine()) != null) {	

				System.out.println(buf);

			}
			reader.close();
		}

	}

最后可以写一个主方法测试一下:

public static void main(String[] args) throws JSchException, IOException {

new Connection().getMessage();

}

得到的截图(我改了代码 多了两行打印):

借鉴:

//在这里使用命令通道比使用shell通道好,不用处理命令提示符
channel = session.openChannel("exec"); 
((ChannelExec) channel).setCommand(command);

1.https://blog.csdn.net/u013066244/article/details/70911585

以上说明了 使用exec 和 shell的区别

2.https://blog.csdn.net/g39173/article/details/53432366

以上说明了session的来源和作用

3.https://blog.csdn.net/he_quotes/article/details/78259849

以上说明了设置  config.put("StrictHostKeyChecking", "no"); 的作用

 

猜你喜欢

转载自blog.csdn.net/qq_28198181/article/details/82789299