func sshSession(user, password, host string, port int) (sshSession *ssh.Session, err error) { //參數: 遠程服務器用戶名, 密碼, ip, 端口
sshClient, err := connector(user, password, host, port) //鏈接ssh
if err != nil {
fmt.Println("鏈接ssh失敗", err)
return
}
if sshSession, err = sshClient.NewSession(); err != nil { //建立客戶端
fmt.Println("建立客戶端失敗", err)
return
}
return
}
func connector(user, password, host string, port int) (sshClient *ssh.Client, err error) {
auth := make([]ssh.AuthMethod, 0)
auth = append(auth, ssh.Password(password))
clientConfig := &ssh.ClientConfig{
User: user,
Auth: auth,
Timeout: 30 * time.Second,
HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {
return nil
},
}
addr := host + ":" + strconv.Itoa(port)
sshClient, err = ssh.Dial("tcp", addr, clientConfig) //鏈接ssh
if err != nil {
fmt.Println("鏈接ssh失敗", err)
return
}
return
}
func main() {
//session, err := go_utils.SshSession("root", "ubZFVU9RSKcTuTZe", "47.107.94.236", 22)
session, err := go_utils.SshSession("root", "Xu765529", "47.92.199.4", 22)
if err != nil {
log.Fatal(err)
}
defer session.Close()
session.Stdout = os.Stdout
session.Stderr = os.Stderr
session.Stdin = os.Stdin
err = session.Run("/usr/local/start.sh") //腳本路徑
if err != nil {
fmt.Println(err)
}
}
看一下腳本內容:
在服務器上直接運行腳本:java
hello world 和 2個java的版本號, 然而程序運行的實際狀況:服務器
有一個java命令報command not found, 是由於ssh在鏈接遠程的環境變量中不包含可執行文件的路徑, 因此要本身加上路徑session