50 lines
1.4 KiB
Python
50 lines
1.4 KiB
Python
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
|