要使用Golang进行SSH远程连接到Linux,并读取文件,你可以使用golang.org/x/crypto/ssh包。以下是一个简单的示例代码:

package main

import (
	"fmt"
	"io/ioutil"
	"log"

	"golang.org/x/crypto/ssh"
)

func main() {
	config := &ssh.ClientConfig{
		User: "username",
		Auth: []ssh.AuthMethod{
			ssh.Password("password"),
		},
		HostKeyCallback: ssh.InsecureIgnoreHostKey(),
	}

	client, err := ssh.Dial("tcp", "remote-host:22", config)
	if err != nil {
		log.Fatalf("Failed to dial: %s", err)
	}
	defer client.Close()

	session, err := client.NewSession()
	if err != nil {
		log.Fatalf("Failed to create session: %s", err)
	}
	defer session.Close()

	output, err := session.Output("cat /path/to/file.txt")
	if err != nil {
		log.Fatalf("Failed to execute command: %s", err)
	}

	fmt.Println(string(output))
}

在上面的代码中,你需要将username替换为远程Linux主机的用户名,password替换为密码,remote-host替换为远程Linux主机的IP地址或域名,/path/to/file.txt替换为要读取的文件路径。

此代码将通过SSH连接到远程主机,使用cat命令读取文件的内容,并将结果打印到控制台上

golang ssh远程连接到linux读取文件

原文地址: https://www.cveoy.top/t/topic/i0wN 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录