gitee.com/h79/goutils@v1.22.10/common/ssh/session.go (about)

     1  package ssh
     2  
     3  import (
     4  	"bytes"
     5  	"golang.org/x/crypto/ssh"
     6  	"time"
     7  )
     8  
     9  type Session struct {
    10  	Host    string //ip:port
    11  	Session *ssh.Session
    12  	Client  *ssh.Client
    13  	config  *ssh.ClientConfig
    14  }
    15  
    16  type Result struct {
    17  	Id         int
    18  	Host       string
    19  	Command    string
    20  	LocalPath  string
    21  	RemotePath string
    22  	Result     string
    23  	StartTime  time.Time
    24  	EndTime    time.Time
    25  	Error      error
    26  }
    27  
    28  func NewSession(host string, conf *ssh.ClientConfig) *Session {
    29  	return &Session{Host: host, config: conf}
    30  }
    31  
    32  func (s *Session) Connect() error {
    33  	if s.Client != nil {
    34  		return s.createSession()
    35  	}
    36  	client, err := ssh.Dial("tcp", s.Host, s.config)
    37  	if err != nil {
    38  		return err
    39  	}
    40  	s.Client = client
    41  	return s.createSession()
    42  }
    43  
    44  func (s *Session) createSession() error {
    45  	if s.Session != nil {
    46  		return nil
    47  	}
    48  	session, err := s.Client.NewSession()
    49  	if err != nil {
    50  		return err
    51  	}
    52  	s.Session = session
    53  	return nil
    54  }
    55  
    56  func (s *Session) Close() {
    57  	if s.Session != nil {
    58  		s.Session.Close()
    59  		s.Session = nil
    60  	}
    61  	if s.Client != nil {
    62  		s.Client.Close()
    63  		s.Client = nil
    64  	}
    65  }
    66  
    67  func (s *Session) Exec(id int, command string) *Result {
    68  
    69  	result := &Result{
    70  		Id:      id,
    71  		Host:    s.Host,
    72  		Command: command,
    73  	}
    74  	if err := s.Connect(); err != nil {
    75  		result.Error = err
    76  		return result
    77  	}
    78  
    79  	var b bytes.Buffer
    80  	var b1 bytes.Buffer
    81  
    82  	s.Session.Stdout = &b
    83  	s.Session.Stderr = &b1
    84  
    85  	start := time.Now()
    86  	if err := s.Session.Run(command); err != nil {
    87  		result.Error = err
    88  		result.Result = b1.String()
    89  		return result
    90  	}
    91  	end := time.Now()
    92  	result.Result = b.String()
    93  	result.StartTime = start
    94  	result.EndTime = end
    95  	return result
    96  }