Vin*_*ent 45
这个答案只是Bradford Medeiros 解决方案的更详细版本,对我来说,这也是最好的答案,所以归功于他。
在他的回答中,他解释了要做什么(命名管道),但没有具体说明如何去做。
我不得不承认,在我阅读他的解决方案时,我不知道什么是命名管道。所以我努力实现它(虽然它实际上很简单),但我确实成功了。所以我的回答的重点只是详细说明为了让它工作而需要运行的命令,但同样,功劳归于他。
在主主机上,选择要放置命名管道文件的文件夹,例如/path/to/pipe/和管道名称,例如mypipe,然后运行:
mkfifo /path/to/pipe/mypipe
Run Code Online (Sandbox Code Playgroud)
管道已创建。类型
ls -l /path/to/pipe/mypipe
Run Code Online (Sandbox Code Playgroud)
并检查以“p”开头的访问权限,例如
prw-r--r-- 1 root root 0 mypipe
Run Code Online (Sandbox Code Playgroud)
现在运行:
tail -f /path/to/pipe/mypipe
Run Code Online (Sandbox Code Playgroud)
终端现在正在等待数据发送到这个管道
现在打开另一个终端窗口。
然后运行:
echo "hello world" > /path/to/pipe/mypipe
Run Code Online (Sandbox Code Playgroud)
检查第一个终端(带有 的终端tail -f),它应该显示“hello world”
在主机容器上,不是运行tail -f它只输出作为输入发送的任何内容,而是运行以下命令将其作为命令执行:
eval "$(cat /path/to/pipe/mypipe)"
Run Code Online (Sandbox Code Playgroud)
然后,从另一个终端,尝试运行:
echo "ls -l" > /path/to/pipe/mypipe
Run Code Online (Sandbox Code Playgroud)
返回第一个终端,您应该会看到ls -l命令的结果。
您可能已经注意到,在上一部分中,在ls -l显示输出后,它立即停止侦听命令。
而不是eval "$(cat /path/to/pipe/mypipe)",运行:
while true; do eval "$(cat /path/to/pipe/mypipe)"; done
Run Code Online (Sandbox Code Playgroud)
(你可以不知道)
现在您可以一个接一个地发送无限数量的命令,它们都将被执行,而不仅仅是第一个。
唯一需要注意的是,如果主机必须重新启动,“while”循环将停止工作。
为了处理重启,这里是我所做的:
把while true; do eval "$(cat /path/to/pipe/mypipe)"; done在一个名为execpipe.sh与#!/bin/bash头
不要忘记chmod +x它
通过运行将其添加到 crontab
crontab -e
Run Code Online (Sandbox Code Playgroud)
然后添加
@reboot /path/to/execpipe.sh
Run Code Online (Sandbox Code Playgroud)
此时,测试一下:重新启动服务器,当它备份时,将一些命令回显到管道中并检查它们是否被执行。当然,您无法看到命令的输出,因此ls -l不会有帮助,但touch somefile会有所帮助。
另一种选择是修改脚本以将输出放在一个文件中,例如:
while true; do eval "$(cat /path/to/pipe/mypipe)" &> /somepath/output.txt; done
Run Code Online (Sandbox Code Playgroud)
现在您可以运行ls -l并且输出(&>在 bash 中使用的 stdout 和 stderr )应该在 output.txt 中。
如果您像我一样同时使用 docker compose 和 dockerfile,这就是我所做的:
假设您要像/hostpipe在容器中一样安装 mypipe 的父文件夹
添加这个:
VOLUME /hostpipe
Run Code Online (Sandbox Code Playgroud)
在您的 dockerfile 中以创建挂载点
然后添加这个:
volumes:
- /path/to/pipe:/hostpipe
Run Code Online (Sandbox Code Playgroud)
在您的 docker compose 文件中,以便将 /path/to/pipe 挂载为 /hostpipe
重新启动您的 docker 容器。
执行到您的 docker 容器中:
docker exec -it <container> bash
Run Code Online (Sandbox Code Playgroud)
进入安装文件夹并检查您是否可以看到管道:
cd /hostpipe && ls -l
Run Code Online (Sandbox Code Playgroud)
现在尝试从容器内运行命令:
echo "touch this_file_was_created_on_main_host_from_a_container.txt" > /hostpipe/mypipe
Run Code Online (Sandbox Code Playgroud)
它应该工作!
警告:如果你有一个 OSX (Mac OS) 主机和一个 Linux 容器,它不会工作(解释在这里/sf/answers/3043229591/和问题在这里https://github.com/docker /for-mac/issues/483 ) 因为管道实现不一样,所以你从 Linux 写入管道的内容只能被 Linux 读取,而你从 Mac OS 写入管道的内容只能被 a 读取Mac OS(这句话可能不太准确,但请注意存在跨平台问题)。
例如,当我从 Mac OS 计算机在 DEV 中运行我的 docker 设置时,上述命名管道不起作用。但是在登台和生产中,我有 Linux 主机和 Linux 容器,它运行良好。
下面是我如何从 Node.JS 容器向主主机发送命令并检索输出:
const pipePath = "/hostpipe/mypipe"
const outputPath = "/hostpipe/output.txt"
const commandToRun = "pwd && ls-l"
console.log("delete previous output")
if (fs.existsSync(outputPath)) fs.unlinkSync(outputPath)
console.log("writing to pipe...")
const wstream = fs.createWriteStream(pipePath)
wstream.write(commandToRun)
wstream.close()
console.log("waiting for output.txt...") //there are better ways to do that than setInterval
let timeout = 10000 //stop waiting after 10 seconds (something might be wrong)
const timeoutStart = Date.now()
const myLoop = setInterval(function () {
if (Date.now() - timeoutStart > timeout) {
clearInterval(myLoop);
console.log("timed out")
} else {
//if output.txt exists, read it
if (fs.existsSync(outputPath)) {
clearInterval(myLoop);
const data = fs.readFileSync(outputPath).toString()
if (fs.existsSync(outputPath)) fs.unlinkSync(outputPath) //delete the output file
console.log(data) //log the output of the command
}
}
}, 300);
Run Code Online (Sandbox Code Playgroud)
Moh*_*din 43
我知道这是一个老问题,但理想的解决方案可能是连接到主机SSH并执行命令,如下所示:
ssh -l ${USERNAME} ${HOSTNAME} "${SCRIPT}"
Run Code Online (Sandbox Code Playgroud)
由于这个答案不断获得投票,我想添加一个注释,用于调用脚本的帐户应该是一个完全没有权限的帐户,但只能将该脚本作为sudo执行(可以从sudo文件中完成) .
Bra*_*ros 28
使用命名管道.在主机操作系统上,创建一个脚本来循环和读取命令,然后在其上调用eval.
让docker容器读取到该命名管道.
为了能够访问管道,您需要通过卷安装它.
这类似于SSH机制(或类似的基于套接字的方法),但是正确地限制了主机设备,这可能更好.另外,您不必传递身份验证信息.
我唯一的警告是要谨慎对待你这样做的原因.如果你想创建一个用户输入或其他任何东西进行自我升级的方法,那完全可以做,但是你可能不想调用命令来获取一些配置数据,因为正确的方法是将它传递给args /卷到docker.同样要谨慎对待你正在评估的事实,所以只需考虑一下权限模型.
其他一些答案(例如在卷下运行脚本)将无法正常工作,因为它们无法访问完整的系统资源,但根据您的使用情况,它可能更合适.
Pau*_*tte 22
这真的取决于你需要bash脚本做什么!
例如,如果bash脚本只是回显一些输出,那么你可以这样做
docker run --rm -v $(pwd)/mybashscript.sh:/mybashscript.sh ubuntu bash /mybashscript.sh
Run Code Online (Sandbox Code Playgroud)
另一种可能性是你希望bash脚本安装一些软件 - 比如安装docker-compose的脚本.你可以做点什么
docker run --rm -v /usr/bin:/usr/bin --privileged -v $(pwd)/mybashscript.sh:/mybashscript.sh ubuntu bash /mybashscript.sh
Run Code Online (Sandbox Code Playgroud)
但在这一点上,你真的需要密切了解脚本正在做什么,以便从容器内部允许主机上所需的特定权限.
小智 10
我的懒惰使我找到了未在此处作为答案发布的最简单的解决方案。
为了从 docker 容器中获得 linux 主机的完整 shell,您需要做的就是:
docker run --privileged --pid=host -it alpine:3.8 \
nsenter -t 1 -m -u -n -i sh
Run Code Online (Sandbox Code Playgroud)
解释:
--privileged : 授予容器额外的权限,它允许容器访问主机 (/dev) 的设备
--pid=host :允许容器使用 Docker 主机(运行 Docker 守护程序的 VM)的进程树 nsenter 实用程序:允许在现有命名空间(为容器提供隔离的构建块)中运行进程
nsenter (-t 1 -m -u -n -i sh) 允许在与 PID 为 1 的进程相同的隔离上下文中运行进程 sh。然后整个命令将在 VM 中提供一个交互式 sh shell
此设置具有重大的安全隐患,应谨慎使用(如果有)。
小智 6
编写一个简单的服务器 python 服务器侦听端口(比如 8080),将端口 -p 8080:8080 与容器绑定,向 localhost:8080 发出 HTTP 请求以询问运行带有 popen 的 shell 脚本的 python 服务器,运行 curl 或编写代码以发出 HTTP 请求 curl -d '{"foo":"bar"}' localhost:8080
#!/usr/bin/python
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
import subprocess
import json
PORT_NUMBER = 8080
# This class will handles any incoming request from
# the browser
class myHandler(BaseHTTPRequestHandler):
def do_POST(self):
content_len = int(self.headers.getheader('content-length'))
post_body = self.rfile.read(content_len)
self.send_response(200)
self.end_headers()
data = json.loads(post_body)
# Use the post data
cmd = "your shell cmd"
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
p_status = p.wait()
(output, err) = p.communicate()
print "Command output : ", output
print "Command exit status/return code : ", p_status
self.wfile.write(cmd + "\n")
return
try:
# Create a web server and define the handler to manage the
# incoming request
server = HTTPServer(('', PORT_NUMBER), myHandler)
print 'Started httpserver on port ' , PORT_NUMBER
# Wait forever for incoming http requests
server.serve_forever()
except KeyboardInterrupt:
print '^C received, shutting down the web server'
server.socket.close()
Run Code Online (Sandbox Code Playgroud)
如果您不担心安全性,而只是希望从另一个 docker 容器(如 OP)中启动主机上的 docker 容器,则可以通过共享主机上的侦听套接字来与 docker 容器共享主机上运行的 docker 服务器。
请参阅https://docs.docker.com/engine/security/security/#docker-daemon-attack-surface并查看您的个人风险承受能力是否允许此特定应用程序。
您可以通过将以下卷参数添加到启动命令中来完成此操作
docker run -v /var/run/docker.sock:/var/run/docker.sock ...
Run Code Online (Sandbox Code Playgroud)
或者通过在 docker compose 文件中共享 /var/run/docker.sock ,如下所示:
version: '3'
services:
ci:
command: ...
image: ...
volumes:
- /var/run/docker.sock:/var/run/docker.sock
Run Code Online (Sandbox Code Playgroud)
当您在 docker 容器中运行 docker start 命令时,主机上运行的 docker 服务器将看到该请求并配置同级容器。
信用:http ://jpetazzo.github.io/2015/09/03/do-not-use-docker-in-docker-for-ci/
我发现使用命名管道的答案很棒。但我想知道是否有办法获取执行命令的输出。
解决方案是创建两个命名管道:
mkfifo /path/to/pipe/exec_in
mkfifo /path/to/pipe/exec_out
Run Code Online (Sandbox Code Playgroud)
然后,按照@Vincent的建议,使用循环的解决方案将变为:
# on the host
while true; do eval "$(cat exec_in)" > exec_out; done
Run Code Online (Sandbox Code Playgroud)
然后在 docker 容器上,我们可以执行命令并使用以下命令获取输出:
# on the container
echo "ls -l" > /path/to/pipe/exec_in
cat /path/to/pipe/exec_out
Run Code Online (Sandbox Code Playgroud)
如果有人感兴趣,我需要从容器在主机上使用故障转移 IP,我创建了这个简单的 ruby 方法:
def fifo_exec(cmd)
exec_in = '/path/to/pipe/exec_in'
exec_out = '/path/to/pipe/exec_out'
%x[ echo #{cmd} > #{exec_in} ]
%x[ cat #{exec_out} ]
end
# example
fifo_exec "curl https://ip4.seeip.org"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
68097 次 |
| 最近记录: |