Golang SSH服务器:如何使用scp处理文件传输?

I have written a small SSH-Server in golang with the crypto/ssh package.

It supports returning an interactive shell and immediate command execution.

Here is a minimal example of the server:

package main

import (
    "fmt"
    "io/ioutil"
    "log"
    "net"
    "os/exec"

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

func main() {
    c := &ssh.ServerConfig{
        PasswordCallback: func(c ssh.ConnMetadata, pass []byte) (*ssh.Permissions, error) {
            if c.User() == "foo" && string(pass) == "bar" {
                return nil, nil
            }
            return nil, fmt.Errorf("password rejected for %q", c.User())
        },
    }

    keyBytes, _ := ioutil.ReadFile("key")
    key, _ := ssh.ParsePrivateKey(keyBytes)
    c.AddHostKey(key)

    listener, _ := net.Listen("tcp", "0.0.0.0:2200")
    for {
        tcpConn, _ := listener.Accept()
        _, chans, reqs, _ := ssh.NewServerConn(tcpConn, c)
        go ssh.DiscardRequests(reqs)
        go handleChannels(chans)
    }
}

func handleChannels(chans <-chan ssh.NewChannel) {
    for newChannel := range chans {
        go handleChannel(newChannel)
    }
}

func handleChannel(newChannel ssh.NewChannel) {
    channel, requests, _ := newChannel.Accept()
    for req := range requests {
        switch req.Type {
        case "shell":
            go handleShell(channel)
        case "exec":
            go handleExec(channel, req)
        }
    }
}

func handleShell(c ssh.Channel) {}
func handleExec(c ssh.Channel, r *ssh.Request) {
    cmdString, args, _ := parseCommand(r.Payload)
    log.Printf("exec: %s
", cmdString)
    for i := range args {
        log.Printf("arg %d: %s
", i, args[i])
    }
    cmd := exec.Command(cmdString, args...)
    cmd.Run()
}

func parseCommand(b []byte) (string, []string, error) {
    cmdString := strings.TrimSpace(string(b))
    cmdArray := strings.Split(cmdString, " ")

    cmd := strings.Trim(cmdArray[0], " ")
    args := cmdArray[1:]

    return cmd, args, nil
}

If I run the server and execute scp as follows:

scp -P 2200 test.file foo@localhost:~/

the handleExec function is called.

The output of the cmdString shows:

2015/11/22 17:49:14 exec: scp
2015/11/22 17:49:14 arg 0: -t
2015/11/22 17:49:14 arg 1: ~/

But how can I implement the handleExec function to actually save the file/dir I passed via scp?

dongxie3701
dongxie3701 您没有要传递给scp命令的文件或目录,该文件或目录是从客户端scp发送的(从技术上讲,scp与ssh无关,它只知道如何调用ssh并将其用作管道)。您需要做的就是将客户端的scp实例与exec'ed命令的stdin和stdout连接。
接近 5 年之前 回复
dtsfnyay300457
dtsfnyay300457 感谢您的帮助,但是我仍然很难解决问题,如何将文件/目录从ssh.Channel传递给我执行的scp命令。
接近 5 年之前 回复
douyanjing8287
douyanjing8287 该命令位于有效负载中,您已经在代码中对其进行了解析。文件通过通道传输,并由您执行的scp命令处理。(至于-t,scp命令不是ssh规范的一部分。opensshscp源可能是所有选项的最佳资源)
接近 5 年之前 回复
douti6740
douti6740 好的,我解析了cmd字符串,将使用给定的参数执行scp命令。但是我完全不知道如何将实际文件传递给scp。它是在r.Payload中还是通过ssh.Channel传输?我什至在scp手册页中找不到-t选项。
接近 5 年之前 回复
drgm51600
drgm51600 首先,首先要正确执行scp命令,要么将其传递给shell,要么自己拆分参数(不记得哪个ssh会这样做)
接近 5 年之前 回复

1个回答

I just ran into the problem of executing scp and custom commands over my ssh server and as it is undocumented how to do this I pieced together some code from the tests in crypto.ssh (https://github.com/golang/crypto/blob/master/ssh/session.go and https://github.com/golang/crypto/blob/master/ssh/session_test.go) It works with OpenSSH and the crypto.ssh client. You can for instance call session.Run() on your client and handle e.g. scp or custom commands with it.

type exitStatusMsg struct {
    Status uint32
}

// RFC 4254 Section 6.5.
type execMsg struct {
    Command string
}

go func(in <-chan *ssh.Request, channel ssh.Channel) {
        for req := range in {
            if req.Type == "exec" {
                var msg execMsg
                if err := ssh.Unmarshal(req.Payload, &msg); err != nil {
                    log.Printf("error parsing ssh execMsg: %s
", err)
                    req.Reply(false, nil)
                    return
                }
                go func(msg execMsg, ch ssh.Channel) {
                    // ch can be used as a ReadWriteCloser if there should be interactivity
                    runYourCommand(msg.Command, ch)
                    ex := exitStatusMsg{
                        Status: 0,
                    }
                    // return the status code
                    if _, err := ch.SendRequest("exit-status", false, ssh.Marshal(&ex)); err != nil {
                        log.Printf("unable to send status: %v", err)
                    }
                    ch.Close()
                }(msg, channel)
                req.Reply(true, nil) // tell the other end that we can run the request
            } else {
                req.Reply(req.Type == "shell", nil)
            }
        }
    }(requests, channel)

You need to replace runYourCommand with whatever function then executes your command and set the exit code to whatever your command/process returns.

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问