Linux桌面操作
更新时间 2026-10-21 10:01:45
最近更新时间: 2026-10-21 10:01:45
前提条件
在控制台完成Linux桌面沙箱模板创建
在执行下文所有代码前,请先按照环境变量设置部分,完成环境变量设置,并将在控制台创建的Linux桌面沙箱模版名称填入下列代码的 template 参数中。
桌面操作
以下示例创建桌面沙箱,启动应用,完成鼠标、键盘、窗口、截图等操作,并开启带鉴权的实时流。更多用法请参考 E2B Desktop 官方文档
说明: 为了保持与 E2B SDK 的兼容,您需要使用 E2B SDK 版本如下:
pip install e2b-code-interpreter==2.6.2
pip install e2b==2.20.3
pip install e2b-desktop==2.3.1
from dotenv import load_dotenv
from e2b_desktop import Sandbox
load_dotenv()
def main():
# 创建沙箱,会同时创建Xvfb and xfce4
desktop = Sandbox.create(template="mylinuxtpl", resolution=(1280,720))
print(" - Desktop Sandbox started, ID:", desktop.sandbox_id)
print("\n> >>>>>>>获取屏幕尺寸")
width, height = desktop.get_screen_size()
print(" - Desktop Sandbox screen size:", width, height)
try:
print("\n> Starting desktop stream...")
desktop.stream.start(require_auth=True)
auth_key = desktop.stream.get_auth_key()
stream_url = desktop.stream.get_url(auth_key=auth_key)
# 可以在浏览器中访问该vnc页面
print(" - Stream URL:", stream_url)
except RuntimeError as e:
print(f"stream 已存在{e}")
desktop.stream.stop()
desktop.stream.start(require_auth=True)
auth_key = desktop.stream.get_auth_key()
stream_url = desktop.stream.get_url(auth_key=auth_key)
print(" - Stream URL:", stream_url)
##############################################################
# 通用操作
##############################################################
print("\n> >>>>>>>启动应用")
# Launch an application
# 可以在 /usr/share/applications下面找到应用名
desktop.launch('xfce4-terminal') # or vscode, firefox, etc.
# 等待5秒应用启动完成
desktop.wait(5000)
print("\n> >>>>>>>获取应用窗口id")
window_ids = desktop.get_application_windows("xfce4-terminal")
print(f"获取xfce4-terminal窗口id是{window_ids}")
print("\n> >>>>>>>运行bash命令前台运行")
# 前台运行
command_result = desktop.commands.run("ls -la /home/user", user="user")
print(f"command_result.stderr: {command_result.stderr}")
print(f"command_result.stdout: {command_result.stdout}")
print(f"command_result.exit_code: {command_result.exit_code}")
print("\n> >>>>>>>运行bash命令后台运行")
# 后台运行
echo_code = """
for i in {1..3}; do
echo -n $i
sleep 1
done
echo done
"""
# 后台执行指令
echo_handler = desktop.commands.run(echo_code, background=True, user="user")
print(f"进程id是:{echo_handler.pid}")
response = echo_handler.wait(on_stdout=lambda data: print(data))
print("\n> >>>>>>>等待1s")
desktop.wait(1000) # Wait for 1 second
##############################################################
# 鼠标操作
##############################################################
print("\n> >>>>>>>鼠标移动")
desktop.move_mouse(100, 200) # Move to x, y coordinates
desktop.wait(1000) # Wait for 1 second
print("\n> >>>>>>>右键单击")
desktop.right_click(x=100, y=200)
desktop.wait(1000) # Wait for 1 second
##############################################################
# 键盘操作
##############################################################
print("\n> >>>>>>>输入文本")
desktop.write("Hello, world!") # Default: chunk_size=25, delay_in_ms=75
desktop.write("Fast typing!", chunk_size=50, delay_in_ms=25) # Faster typing
print("\n> >>>>>>>键盘按下")
# Press keys
desktop.press("enter")
desktop.press("space")
desktop.press("backspace")
desktop.press(["ctrl", "c"]) # Key combination
##############################################################
# 窗口控制
##############################################################
print("\n> >>>>>>>获取当前窗口id")
# Get current (active) window ID
window_id = desktop.get_current_window_id()
print(f"获取当前窗口id:{window_id}")
print("\n> >>>>>>>获取当前窗口标题")
# Get window title
title = desktop.get_window_title(window_id)
print(f"获取当前窗口标题:{title}")
##############################################################
# 文件操作
##############################################################
print("\n> >>>>>>>写入文件")
desktop.files.write("/home/user/index.js", "console.log('hello')", user="user")
print("\n> >>>>>>>读取文本文件")
result_text = desktop.files.read("/home/user/index.js", "text", user="user")
print(f"读取到文件内容text格式内容是:{result_text}")
print("\n> >>>>>>>删除文件")
desktop.files.remove("/home/user/index.js", user="user")
print("\n> >>>>>>>截图")
image = desktop.screenshot()
with open("screenshot.png", "wb") as f:
f.write(image)
##############################################################
# 关闭
##############################################################
desktop.stream.stop()
desktop.kill()
if __name__ == "__main__":
main()