your-workflow/backend/app/nodes/cmd_node.py

50 lines
1.4 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from core.pocket_flow import AsyncNode
from core.logger import logger
import asyncio
import asyncssh
async def async_run_cmd(
cmd: str, host: str = None, user: str = None, password: str = None
):
"""
异步执行命令
- 如果 host=None则在本地执行
- 如果 host 不为空,则通过 SSH 执行远程命令
"""
if host is None:
# 本地执行
proc = await asyncio.create_subprocess_shell(
cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE
)
stdout, stderr = await proc.communicate()
return proc.returncode, stdout.decode(), stderr.decode()
else:
# 远程执行
conn = await asyncssh.connect(
host,
username=user,
password=password,
known_hosts=None, # 不检查 known_hosts
)
result = await conn.run(cmd, check=False)
await conn.close()
return result.exit_status, result.stdout, result.stderr
class CMDNode(AsyncNode):
async def prep_async(self, shared):
pass
async def exec_async(self, prep_res):
cmd = self.params.get("cmd")
_, out, err = await async_run_cmd(cmd)
if out:
logger.info(out)
if err:
logger.error(err)
return
async def post_async(self, shared, prep_res, exec_res):
pass