AI-python代码使用deepseek

1,功能

使用trae工具编写python代码,通过提问题给线上大模型工具,让使用ssh自动登录远程靶机做配置文件中字段校验,输出json结果数据。

2,使用工具和流程

开发工具:

使用流程:

  • 注册/登录 SiliconFlow 平台 https://cloud.siliconflow.cn/account/ak
  • 打开这个链接去到 API Key 管理页
  • 点击按钮 创建新的 API Key
  • 把生成的密钥复制下来,用到调用 API 的代码或配置里去
  • 这样你的应用才能访问他们的平台服务。

3,测试代码

ssh_exec_cmd.py:

python 复制代码
import paramiko


class ClientSsh:
    def __init__(self, hostname, port, username, password):
        self.client = self.create_connection(
            hostname=hostname,
            port=port,
            username=username,
            password=password
        )

    @classmethod
    def create_connection(cls, hostname, port, username, password, timeout=10):
        client = paramiko.SSHClient()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        client.connect(hostname, port=port, username=username,
                       password=password, timeout=timeout)
        return client

    def exec_command(self, command, timeout=30):
        stdin, stdout, stderr = self.client.exec_command(command, timeout=timeout)
        out = stdout.read().decode().strip()
        err = stderr.read().decode().strip()
        exit_status = stdout.channel.recv_exit_status()
        return {'stdout': out, 'stderr': err, 'exit_status': exit_status}

    def close(self):
        self.client.close()

tools_call.py:

python 复制代码
import traceback
import json
import time

from openai import OpenAI
from ssh_exec_cmd import ClientSsh

ai_client = OpenAI(
    api_key="xxx",  # 从https://cloud.siliconflow.cn/account/ak获取
    base_url="https://api.siliconflow.cn/v1"
)

def ssh_exec_cmd(command, timeout=30):
    return ssh_client.exec_command(command=command, timeout=timeout)

tools = [
    {
        'type': 'function',
        'function': {
            'name': 'ssh_exec_cmd',
            'description': '远程执行命令并获取输出结果',
            'parameters': {
                'type': 'object',
                'properties': {
                    'command': {
                        'type': 'string',
                        'description': '可执行的命令',
                    },
                    'timeout': {
                        'type': 'integer',
                        'description': '命令执行超时时间(秒)',
                        'default': 30
                    },
                },
                'required': ['command'],
            },
        }
    }
]

# 简化版:只调用一次create方法
def function_call_playground(prompt):
    # 调用AI模型并返回JSON格式结果
    response = ai_client.chat.completions.create(
        model="deepseek-ai/DeepSeek-V3.2",
        messages=[
            {'role': 'user', 'content': prompt}
        ],
        temperature=0.01,
        stream=False,
        tools=tools,
        response_format={"type": "json_object"}
    )
    
    # 返回JSON格式数据
    return response.choices[0].message.content


def verification_example():
    prompt = '''1. 必须调用 ssh_exec_cmd 工具执行命令获取远程主机的真实配置,不得假设或编造结果。
    2. 根据工具返回的实际输出,对照以下合规标准进行判断;
    3. 不得跳过工具调用,不得虚构或假设系统状态。    

核查项详情:核查项名称|核查是否启用root ssh访问。
核查步骤:查看 /etc/ssh/sshd_config 中PermitRootLogin字段值是否为yes,且没有被注释掉,说明是合规,否则不合规。
请以JSON格式返回结果,包含以下字段:
- name: 核查项名称
- result: 核查结果(合规/不合规)
- actual_value: 实际值
- expected_value: 期望值
'''

    result = json.loads(function_call_playground(prompt))
    print(result)

def _escape_cell(content):
    if content is None:
        return "``"
    s = str(content)
    # 转义反引号
    s = s.replace("`", "\\`")
    # 可选:将换行替换为 <br>(仅当你确定渲染器支持 HTML)
    # s = s.replace("\n", "<br>")
    return f"`{s}`"


if __name__ == '__main__':
    connect_host_args = {
        "hostname": 'xxx',
        "port": 22,
        "username": "root",
        "password": "xxx"
    }
    ssh_client = ClientSsh(**connect_host_args)

    try:
        # 此函数处理单个核查项的校验
        verification_example()
    except Exception:
        print(traceback.format_exc())
    finally:
        ssh_client.close()
        ai_client.close()

4,验证结果

相关推荐
人工智能训练3 小时前
【极速部署】Ubuntu24.04+CUDA13.0 玩转 VLLM 0.15.0:预编译 Wheel 包 GPU 版安装全攻略
运维·前端·人工智能·python·ai编程·cuda·vllm
乱世刀疤5 小时前
OpenCode在Windows上的安装与使用入门 | 保姆级教程
ai编程
github.com/starRTC12 小时前
Claude Code中英文系列教程25:非交互式运行 Claude Code
人工智能·ai编程
玄同76516 小时前
Trae国际版与国内版深度测评:AI原生IDE的双生花
ide·人工智能·ai编程·cursor·ai-native·trae
乱世刀疤16 小时前
Claude Code实战:生成植物大战僵尸游戏
ai编程
nbsaas-boot17 小时前
如何进行 Vibe Coding:从“灵感驱动”到“可交付工程”的方法论
java·ai编程
LinkZ-Dev19 小时前
521-解决谷歌 Antigravity 软件登录相关问题
ai编程·gemini·antigravity
玉梅小洋1 天前
Claude Code 从入门到精通(七):Sub Agent 与 Skill 终极PK
人工智能·ai·大模型·ai编程·claude·ai工具
-嘟囔着拯救世界-1 天前
【保姆级教程】Win11 下从零部署 Claude Code:本地环境配置 + VSCode 可视化界面全流程指南
人工智能·vscode·ai·编辑器·html5·ai编程·claude code
小小管写大大码1 天前
如何让vscode变得更智能?vscode接入claude实现自动编程
运维·ide·vscode·自动化·编辑器·ai编程·腾讯云ai代码助手