Python实现通过Web执行Docker容器里面的shell命令

其实就是通过flask接受url传递过来的命令,然后调用SDK相关API执行docker exec命令,然后将结果返回给页面。

1
pip install flask docker
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# coding: utf-8
from flask import Flask
from flask import render_template
from flask import request
import docker

app = Flask(__name__, template_folder='./templates', static_folder="", static_url_path="")
client = docker.from_env()


@app.route('/cmd', methods=['GET', 'POST'])
def exec_cmd():
if request.method == 'GET':
return render_template('cmd.html')
if request.method == 'POST':
container = client.containers.get('gmb-index') # 这里我写死了获取本地这个容器
cmd = request.form.get('cmd')
result = container.exec_run(cmd=cmd)
output = result.output.decode()
return render_template('cmd.html', output=output)


if __name__=='__main__':
app.run(host='127.0.0.1', port=8888)

模板

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Console</title>
</head>
<body>
<div>
<form action="/cmd" method="post">
<input type="text" name="cmd">
<input type="submit" value="Submit">
</form>

<textarea rows="100" cols="200" readonly="readonly">
{{ output }}
</textarea>
</div>
</body>
</html>

如图:

截图

参考资料

关注公众号 尹安灿