使用ssh远程操作文件, 主要是创建ssh, 直接上代码
import ( "fmt" "github.com/pkg/sftp" "golang.org/x/crypto/ssh" "net" "strconv" "time") func SftpConnect(user, password, host string, port int) (sftpClient *sftp.Client, err error) { //参数: 远程服务器用户名, 密码, ip, 端口 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 } if sftpClient, err = sftp.NewClient(sshClient); err != nil { //创建客户端 fmt.Println("创建客户端失败", err) return } return} 使用也很简单
sftpClient.Open() 返回的是*sftp.File, 操作和官方库差不多
原文地址:https://www.cnblogs.com/-xuzhankun/p/11056576.html
时间: 2024-11-02 09:49:02