[Docker] Obtain host information and execute host scripts in the docker container

Ideas

We can remotely connect to the host within the container and then operate the host.

Use sshpass (mine is CentOS 7.9 environment)

1.Install sshpass

apt-get update //更新一下
apt-get -y install sshpass //安装 

2. Connect to the host and execute the command

 sshpass -p '宿主机用户密码' ssh -o StrictHostKeyChecking=no -p 22 用户名@宿主机ip 命令
 列如:
  注意:这是在容器中运行的,查出了宿主机的ip配置信息。
  sshpass -p 'abc@1234' ssh -o StrictHostKeyChecking=no -p 22 [email protected] ifconfig 
  

Insert image description here

3. Connect and execute the host script

vim hello.sh //在宿主机建一个脚本文件

脚本内容
#!/bin/bash
echo "hello woshikunkun"

 注意:这是在容器中运行的,执行了宿主机的脚本。
  sshpass -p 'abc@1234' ssh -o StrictHostKeyChecking=no -p 22 [email protected] sh hello.sh

Insert image description here

4. Of course, it can also be automated. For example, the java project is deployed in a docker container, and then the java project executes the host's script or host's command at a certain moment.

Note: You must first install the sshpass command. Dockerfile files can be automatically installed when you deploy the container.
Docker deploys springboot project


Runtime rt = Runtime.getRuntime();

//执行 ifconfig -a 命令,查询宿主机的ip配置
String[] shell = {
    
    "/bin/bash", "-c", "sshpass -p 'abc@1234' ssh -o StrictHostKeyChecking=no -p 22 [email protected] ifconfig -a "};

//执行hello.sh 脚本
String[] shell = {
    
    "/bin/bash", "-c", "sshpass -p 'abc@1234' ssh -o StrictHostKeyChecking=no -p 22 [email protected] sh hello.sh "};
Process exec = Runtime.getRuntime().exec(shell);
BufferedReader in = null;
try {
    
    
    in = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String str = null;
    String[] strArray = null;
    //逐一对每行内容进行操作
    while ((str = in.readLine()) != null) {
    
    
    	System.out.println(str);
    }
} catch (Exception e) {
    
    
    System.out.println(e);
} finally {
    
    
    in.close();
}

Guess you like

Origin blog.csdn.net/twotwo22222/article/details/128954014