使用go语言的golang.org/x/crypto/ssh包,执行远程机器上的进程检查命令
ps -ef | grep -s buildapp.sh | grep -v grep一直报错
Error: Process exited with status 1
package main
import (
"fmt"
"github.com/pkg/sftp"
"golang.org/x/crypto/ssh"
"os"
"path"
"time"
)
func main() {
localFile := "/test"
remoteDir := "/test/test"
user := "wanglulu"
pass := "123123"
host := "192.168.7.100"
port := 22
//创建SSH Client
sshClient, err := GetSSHClient(user, pass, host, port)
if err != nil {
fmt.Println("Error:",err)
return
}
defer sshClient.Close()
//创建SSH Session
session, err := GetSSHSession(sshClient)
if err != nil {
fmt.Println("Error:",err)
return
}
defer session.Close()
//检查是否有构建任务正在执行
c := `ps -ef | grep -s buildapp.sh | grep -v "grep"`
resp, err := session.Output(c)
if err != nil {
fmt.Println("Error:",err)
return
}
fmt.Println("[INFO]", string(resp))
//创建SSH Session
sftpClient, err := GetSFTPClient(sshClient)
if err != nil {
fmt.Println("Error:",err)
return
}
defer sftpClient.Close()
//传输构建APP需要的资源文件
srcFile, err := os.Open(localFile)
if err != nil {
fmt.Println("Error:",err)
return
}
defer srcFile.Close()
remoteFileName := path.Base(localFile)
dstFile, err := sftpClient.Create(path.Join(remoteDir, remoteFileName))
if err != nil {
fmt.Println("Error:",err)
return
}
defer dstFile.Close()
buf := make([]byte, 1024)
for {
n, _ := srcFile.Read(buf)
if n == 0 {
break
}
dstFile.Write(buf[0:n])
}
}
func GetSSHClient(user, password, host string, port int) (*ssh.Client, error) {
var (
auth []ssh.AuthMethod
addr string
clientConfig *ssh.ClientConfig
client *ssh.Client
err error
)
// get auth method
auth = make([]ssh.AuthMethod, 0)
auth = append(auth, ssh.Password(password))
clientConfig = &ssh.ClientConfig{
User: user,
Auth: auth,
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
Timeout: 60 * time.Second,
}
// connect to ssh
addr = fmt.Sprintf("%s:%d", host, port)
if client, err = ssh.Dial("tcp", addr, clientConfig); err != nil {
return nil, err
}
return client, nil
}
func GetSFTPClient(sshClient *ssh.Client) (*sftp.Client, error) {
var (
sftpClient *sftp.Client
err error
)
// create sftp client
if sftpClient, err = sftp.NewClient(sshClient); err != nil {
return nil, err
}
return sftpClient, nil
}
func GetSSHSession(sshClient *ssh.Client) (*ssh.Session, error) {
var (
session *ssh.Session
err error
)
// create session
if session, err = sshClient.NewSession(); err != nil {
return nil, err
}
return session, nil
}
有疑问加站长微信联系(非本文作者)