3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

DockerでSFTPサーバ立ててGoでアクセスしてみる

Posted at

最初に

GoのSFTPパッケージ触りたかったけど、サーバ立てるのも面倒だったのでコンテナでサクッとやっちゃおうと思ったメモ

SFTPサーバ立てるメモ

atmoz/sftpを使って

docker-compose.yml
version: '3'

services:
  sftp:
    image: atmoz/sftp
    container_name: sftp-server
    volumes:
      - ./sftp-server/upload:/home/foo/upload
    ports:
      - "2222:22"
    command: foo:pass:::upload

な感じでyaml用意して

mkdir sftp-server
mkdir sftp-server/upload
docker-compose up -d --build
sftp -oPort="2222" foo@localhost

な感じでコマンド叩いて、パスワードにpassって入れたら接続できる。

sftp> cd upload
sftp> put test
sftp> exit

な感じでupload以下にファイル配置OK

Go

SFTPが用意できたので、github.com/pkg/sftpgolang.org/x/crypto/sshのサンプル参考に

main.go
package main

import (
	"fmt"
	"log"
	"os"

	"github.com/pkg/sftp"
	"golang.org/x/crypto/ssh"
)

func main() {
	if err := Main(); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}

func Main() error {
	host := "localhost"
	port := "2222"
	user := "foo"
	pass := "pass"

	fmt.Println("Create sshClientConfig")
	sshConfig := &ssh.ClientConfig{
		User: user,
		Auth: []ssh.AuthMethod{
			ssh.Password(pass),
		},
		HostKeyCallback: ssh.InsecureIgnoreHostKey(),
	}

	fmt.Println("SSH connect")
	addr := fmt.Sprintf("%s:%s", host, port)
	fmt.Println(addr)

	conn, err := ssh.Dial("tcp", addr, sshConfig)
	if err != nil {
		return err
	}

	fmt.Println("open an SFTP session over an existing ssh connection")
	client, err := sftp.NewClient(conn)
	if err != nil {
		return err
	}
	defer client.Close()

	fmt.Println("walk a directory")
	w := client.Walk("./")
	for w.Step() {
		if w.Err() != nil {
			continue
		}
		log.Println(w.Path())
	}

	fmt.Println("leave your mark")
	f, err := client.Create("./upload/hello.txt")
	if err != nil {
		return err
	}
	if _, err := f.Write([]byte("Hello world!")); err != nil {
		return err
	}
	f.Close()

	fmt.Println("check it's there")
	fi, err := client.Lstat("./upload/hello.txt")
	if err != nil {
		return err
	}
	log.Println(fi)

	return nil
}

な感じで接続OK

kotaoue/go-sftpにコードおいておく 🐓

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?