1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 |
- package remote
- import (
- "fmt"
- "golang.org/x/crypto/ssh"
- )
- // SSHClient 封装SSH连接配置
- type SSHClient struct {
- Id string
- Username string
- Password string
- Host string
- Port string
- client *ssh.Client
- }
- // NewSSHClient 创建SSH连接
- func NewSSHClient(Id, username, password, host, port string) (*SSHClient, error) {
- config := &ssh.ClientConfig{
- User: username,
- Auth: []ssh.AuthMethod{
- ssh.Password(password),
- },
- HostKeyCallback: ssh.InsecureIgnoreHostKey(),
- }
- client, err := ssh.Dial("tcp", host+":"+port, config)
- if err != nil {
- return nil, fmt.Errorf("无法连接到服务器 %s: %v", host, err)
- }
- return &SSHClient{
- Id: Id,
- Username: username,
- Password: password,
- Host: host,
- Port: port,
- client: client,
- }, nil
- }
- // Close 关闭SSH连接
- func (c *SSHClient) Close() {
- if c.client != nil {
- c.client.Close()
- }
- }
- // RunCommand 在远程服务器上执行命令
- func (c *SSHClient) RunCommand(cmd string) (string, error) {
- session, err := c.client.NewSession()
- if err != nil {
- return "", err
- }
- defer session.Close()
- output, err := session.CombinedOutput(cmd)
- if err != nil {
- return "", fmt.Errorf("无法执行命令: %v", err)
- }
- return string(output), nil
- }
|