模拟docker exec-与python contid bash,同时能够通过python发送命令

发布于 2025-02-02 12:10:29 字数 523 浏览 2 评论 0原文

我希望能够使用Python模拟交互模式。

例如,如果我写

Docker Exec -IT C2 Bash,然后是CD /Home,我将能够看到我在做什么以及在哪里。我试图通过Python多次进行多次操作,但是我能做的最好的方法就是将命令转发到来自父装容器的Docker容器中 - 没有对屏幕上实际发生的事情的任何反馈。

from subprocess import Popen, PIPE
import pty

master,slave = pty.openpty()

print(master)
print(slave)
p = Popen(["docker", "exec", "-i", "c2" ,"/bin/bash"], stdin=PIPE)
p.communicate("cd /home;mkdir 1231321".encode())

该代码有效,没有输出。另外,脚本会自动退出容器,而没有我发送“退出”命令,这不是我想要的。

我很好奇,如果可以通过Python脚本执行此类任务?

谢谢。

I would like to be able to simulate the interactive mode with Python.

For example, if I write

docker exec -it c2 bash, followed by a cd /home, I will be able to see what I am doing and where I am. I tried to do so several times and in a several ways via Python, but the best I can do is just forward a command to a docker container from a parent container - without any feedback on what's actually happening on the screen.

from subprocess import Popen, PIPE
import pty

master,slave = pty.openpty()

print(master)
print(slave)
p = Popen(["docker", "exec", "-i", "c2" ,"/bin/bash"], stdin=PIPE)
p.communicate("cd /home;mkdir 1231321".encode())

This code works, with no output. Also, the script automatically exits the container, without me sending "exit" command, which is not something that I want.

I'm curious, if it's possible to do such task, via a python script?

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

苏辞 2025-02-09 12:10:29

我找到了一种实现我想做的事情,在下面留下答案,因为这可能对某人有帮助。

为了模拟交互式模式,我使用了Python Pexpect库。以下格式应该解决问题。

p = pexpect.spawn(cmd)
p.expect(/regex/)
p.sendline("what you'd like to send")

重复。

I found a way to achieve what I wanted to do in the beginning, leaving answer below since it may be helpful to someone.

In order to simulate interactive mode, I used python pexpect library. Following format should do the trick.

p = pexpect.spawn(cmd)
p.expect(/regex/)
p.sendline("what you'd like to send")

Repeat.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文