python docker client

本文探讨了如何利用DockerClient执行主机命令的方法,重点介绍了exec_create和create_container两个API的功能及参数设置,并对比了它们与docker exec和docker run命令的相似之处。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

参考文档:https://docker-py.readthedocs.io/en/stable/index.html

 

在esc机器上执行命令,可采用两种方案:

一是使用docker client现有的api,需要达到可以执行主机命令的目的。

二是在agent镜像上加个方法,让docker client远程启动这个镜像执行。

 

所以先需要调研下docker client有哪些可以执行主机命令。

注:

Docker Client是Docker提供给用户的客户端。Docker Client提供给用户一个终端,用户输入Docker提供的命令来管理本地或者远程的服务器。

通过参阅文档,发现有两个方法可实现cmd命令:exec_create和create_container。

首先exec_create:


exec_create(containercmdstdout=Truestderr=Truestdin=Falsetty=Falseprivileged=Falseuser=''environment=Noneworkdir=Nonedetach_keys=None)

Sets up an exec instance in a running container。exec_create相当与docker exec命令 :在运行的容器中执行命令

 

Parameters:
  • container (str) – Target container where exec instance will be created
  • cmd (str or list) – Command to be executed
  • stdout (bool) – Attach to stdout. Default: True
  • stderr (bool) – Attach to stderr. Default: True
  • stdin (bool) – Attach to stdin. Default: False
  • tty (bool) – Allocate a pseudo-TTY. Default: False
  • privileged (bool) – Run as privileged.
  • user (str) – User to execute command as. Default: root
  • environment (dict or list) – A dictionary or a list of strings in the following format ["PASSWORD=xxx"] or {"PASSWORD":"xxx"}.
  • workdir (str) – Path to working directory for this exec session
  • detach_keys (str) – Override the key sequence for detaching a container. Format is a single character [a-Z] or ctrl-<value> where <value> is one of: a-z, @, ^, [, , or _. ~/.docker/config.json is used by default.
Returns:

A dictionary with an exec Id key.

Return type:

(dict)

Raises:

docker.errors.APIError – If the server returns an error.

然后是create_container:


create_container(imagecommand=Nonehostname=Noneuser=Nonedetach=Falsestdin_open=Falsetty=Falseports=Noneenvironment=Nonevolumes=Nonenetwork_disabled=Falsename=Noneentrypoint=Noneworking_dir=Nonedomainname=Nonehost_config=Nonemac_address=Nonelabels=Nonestop_signal=Nonenetworking_config=Nonehealthcheck=Nonestop_timeout=Noneruntime=Noneuse_config_proxy=False)

Creates a container. Parameters are similar to those for the docker runcommand except it doesn't support the attach options (-a).

The arguments that are passed directly to this function are host-independent configuration options. Host-specific configuration is passed with the host_config argument. You’ll normally want to use this method in combination with the create_host_config() method to generate host_config.

create_container类似与docker run命令:创建一个新的容器并运行一个命令。指示它不支持-a参数

 

pip install docker

pip install docker-compose

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值