Я делаю проект, чтобы ollama помог мне поддерживать инфраструктуру Linux, и мне нужен IA для подключения к данному ssh-серверу с заданными учетными данными, выполнения команды и передачи вывода команды в чат.
Я уже делал этот код, но он не работает, что-то (в зависимости от того, как я задаю подсказку) я вижу ssh-соединение на сервере, но вывода не возвращается.
это код инструмента, который я использую:
title: ssh connection
description
import os
import requests
from pydantic import BaseModel, Field
import paramiko
class Tools:
class Valves(BaseModel):
SSH_HOST: str = Field(
default = "111.111.111.111", description = "Adress to connect to ssh"
)
SSH_USERNAME: str = Field(
default = "adminuser", description = "Username to use on ssh server"
)
SSH_PASSWORD: str = Field(
default = "thePassword123!", description = "Password to connect on ssh server"
)
pass
class UserValves(BaseModel):
SSH_COMMAND: str = Field(
default = "ifconfig",
description = "user given command trought the chat",
)
pass
def __init__(self):
self.citation = True
self.Valves = self.Valves()
pass
# pass
def connect_ssh(
self, ssh_ip: str, ssh_username: str, ssh_password: str, ssh_command: str
) -> str:
"""
create a ssh connection using the data the user entered on the prompt,
This is the way you can connect to a ssh server, get the ssh_ip, ssh_username, ssh_password and ssh_command from the user prompt em use it to call the function paramiko.
use the bellow function to connect ssh servers and do what the user are asking
:param: ssh_command Command to be executed on ssh connection
:param: ssh_username username to log in in to ssh server
:param: ssh_password password to use on log in to ssh server
:param: ssh_host hostname or ip to open ssh connection
:output: A string containing the output got after command issued, and will be returned to user.
"""
"""
check if the informations for connect ssh is fullfilled
"""
if not self.Valves.SSH_IP:
return "Let the user know the ip to ssh connection was not provided. User will tell the ssh_host trought chat" ###
if not self.Valves.SSH_USERNAME:
return "Let the user know the username to ssh connection was not provided. User will tell the ssh_username trought chat"
if not self.Valves.SSH_PASSWORD:
return "Let the user know the password was not provided. User will tell the ssh_password trought chat"
if not self.UserValves.SSH_COMMAND:
return "Let the user know the ssh command was not provided. User will tell the ssh_command trought chat"
"""
use this function to connect to a ssh server, using parameters given by the user
"""
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(
self.UserValves.SSH_IP,
username=self.Valves.SSH_USERNAME,
password=self.Valves.SSH_PASSWORD,
)
stdin, stdout, stderr = ssh.exec_command(self.UserValves.SSH_COMMAND)
"""
get the output of the command and return to the chat.
"""
if stdout:
output += stdout.read().decode()
if stderr:
output += stderr.read().decode()
return "say that the command was executed, and you are waiting the output to tell on chat"
ssh.close()
return output
не видел этого, код отформатирован.
Привет, спасибо за переформатирование, это настоящий код, который вы написали для него, или псевдокод? Я дал ответ, посмотрим, что произойдет.
это код, который я написал для него.
Я еще не активировал инструмент, пытаясь понять, почему. Ответ от ИИ: «Я не могу установить ssh-соединение…» Я интенсивно работаю над этим и дам вам отзыв, как только получу результат. Большое спасибо за ваше время.
занимайте столько времени, сколько захотите, я всегда рад помочь.
Я думаю, вы на правильном пути. Вот некоторые проблемы, которые я заметил.
Проблемы:
У вас неверная ссылка на объект для всех инициализированных переменных: в вашем коде есть ссылка на self.UserValves.SSH_IP
, которая неверна, поскольку SSH_IP
не определена в UserValves
. Вместо этого он должен ссылаться на self.Valves.SSH_HOST
.
У вас неправильное использование переменной: вы не инициализировали выходную переменную перед ее использованием для получения выходных данных stdout
и stderr
.
Я внес необходимые исправления. Вот исправленный код, который поможет вам решить проблему. Надеюсь, это поможет тебе.
import os
from pydantic import BaseModel, Field
import paramiko
class Tools:
class Valves(BaseModel):
SSH_HOST: str = Field(
default = "111.11.111.111", description = "Address to connect to SSH"
)
SSH_USERNAME: str = Field(
default = "adminuser", description = "Username to use on SSH server"
)
SSH_PASSWORD: str = Field(
default = "thePassword123123", description = "Password to connect on SSH server"
)
class UserValves(BaseModel):
SSH_COMMAND: str = Field(
default = "ifconfig",
description = "User-given command through the chat",
)
def __init__(self):
self.citation = True
self.Valves = self.Valves()
self.UserValves = self.UserValves()
def connect_ssh(self) -> str:
"""
create a ssh connection using the data the user entered on the prompt,
This is the way you can connect to a ssh server, get the ssh_ip, ssh_username, ssh_password and ssh_command from the user prompt em use it to call the function paramiko.
use the bellow function to connect ssh servers and do what the user are asking
:param: ssh_command Command to be executed on ssh connection
:param: ssh_username username to log in in to ssh server
:param: ssh_password password to use on log in to ssh server
:param: ssh_host hostname or ip to open ssh connection
:output: A string containing the output got after command issued, and will be returned to user.
"""
"""
check if the informations for connect ssh is fullfilled
"""
if not self.Valves.SSH_HOST:
return "Let the user know the ip to ssh connection was not provided. User will tell the ssh_host trought chat" ###
if not self.Valves.SSH_USERNAME:
return "Let the user know the username to ssh connection was not provided. User will tell the ssh_username trought chat"
if not self.Valves.SSH_PASSWORD:
return "Let the user know the username to ssh connection was not provided. User will tell the ssh_username trought chat"
if not self.UserValves.SSH_COMMAND:
return "Let the user know the ssh command was not provided. User will tell the ssh_command thought chat"
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(
self.Valves.SSH_HOST,
username=self.Valves.SSH_USERNAME,
password=self.Valves.SSH_PASSWORD,
)
stdin, stdout, stderr = ssh.exec_command(self.UserValves.SSH_COMMAND)
# Read output
output = ""
if stdout:
output += stdout.read().decode()
if stderr:
output += stderr.read().decode()
# Close SSH connection
ssh.close()
if output.strip():
return output
else:
return "command worked, but no output "
except Exception as e:
return f"Error: {str(e)}"
Я думаю, что код Python правильный (Дерек сделал его лучше), но у меня проблема с тем, чтобы оллама запускала часть кода с параметрами. Когда я прошу установить соединение по ssh, он имитирует его или просто говорит, что не может этого сделать. Правильное поведение должно заключаться в выполнении части paramiko и возврате вывода в чат.
@Педро, могу ли я предложить вам использовать ссылку-> Crew-ai для запуска ssh, а не ollama, выполняющего всю работу, и выделить другого агента для бита ssh вместо ollama или другой модели?
Я мог бы протестировать и даже сказать, что открыть ssh-соединение невозможно, вызывается paramiko (я вижу, что ssh-соединение поступает на сервер), но возврат не отображается. Как я могу сообщить ламе, что при этом он способен использовать SSH?
Вы вообще тренировали модель или она из коробки(как будто только что скачали)? какую модель вы используете llama3? возможно, у удаленного сервера, который вы используете, есть ограничения, пробовали ли вы, можете ли вы подключиться к нему по SSH без использования ollama?
Да, я использую llama3 из коробки, ssh работает, когда я пробую Python в CLI Linux, он работает отлично, я думаю, проблема в том, что я не знаю, как параметризовать ИНСТРУМЕНТ OpenWebUI, чтобы делать то, что я хочу, я думаю, что это на данный момент подскажите больше, чем код.
Можете ли вы вместо этого попробовать инструменты langchain, они очень полезны. Другое решение, если вы хотите использовать openwebuitool, — передать скрипт Python для запуска олламы следующим образом await __event_emitter__({"type":subprocess.run(command=ssh into machine, shell=True, check=True) , "data":{"content": "This message will be appended to the chat."}})
можешь переформатировать свой код