我正在尝试在GO中实现SSH服务器,它充当SCP接收器(无需调用外部scp
命令(
我最终得到了部分工作代码:https://gist.github.com/Seitanas/ad02158e8d5d2acedd9e7973ae44c77c.问题是,当我尝试将文件scp到此服务时,本地scp客户端正确复制数据,但返回1。
我认为通道关闭时发生了一些事情。也许我在SCP协议中遗漏了什么?我猜ssh返回-1
,然后scp
以1
退出测试结果:
echo "contents"> test.txt
scp -v -P2222 test.txt foo@127.0.0.1:/
Executing: program /usr/bin/ssh host 127.0.0.1, user foo, command scp -v -t /
...
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: password
debug1: Next authentication method: password
foo@127.0.0.1's password:
debug1: Authentication succeeded (password).
Authenticated to 127.0.0.1 ([127.0.0.1]:2222).
debug1: channel 0: new [client-session]
debug1: Requesting no-more-sessions@openssh.com
debug1: Entering interactive session.
debug1: pledge: network
debug1: Sending environment.
debug1: Sending env LC_TERMINAL_VERSION = 3.4.12
debug1: Sending env LC_CTYPE = en_US.UTF-8
debug1: Sending env LC_TERMINAL = iTerm2
debug1: Sending command: scp -v -t /
Sending file modes: C0644 9 test.txt
test.txt 0% 0 0.0KB/s --:-- ETAdebug1: channel 0: free: client-session, nchannels 1
test.txt 100% 9 21.4KB/s 00:00
debug1: fd 0 clearing O_NONBLOCK
Transferred: sent 2032, received 1116 bytes, in 0.0 seconds
Bytes per second: sent 1245098.0, received 683823.5
debug1: Exit status -1
echo $?
1
go代码输出:
go run test.go
2022/02/15 17:17:21 Command: C
2022/02/15 17:17:21 File info: 0644 9 test.txt
2022/02/15 17:17:21 File size: 9
2022/02/15 17:17:21 Content: contents
谢谢你的意见。
好的,我发现了问题所在。我忘了我在模拟SCP二进制蚂蚁服务器端,所以我也需要模拟它的退出代码。所以我在末尾添加了一行:
channel.SendRequest("exit-status", false, []byte{0, 0, 0, 0})
这将通过通道发送exit 0
状态。如果没有它,客户端的SCP正在等待远程传输完成,但套接字在传输后立即关闭,没有退出代码。
现在一切如预期:
debug1: Sending command: scp -v -t /
Sending file modes: C0644 9 test.txt
test.txt 0% 0 0.0KB/s --:-- ETAdebug1: client_input_channel_req: channel 0 rtype exit-status reply 0
debug1: channel 0: free: client-session, nchannels 1
test.txt 100% 9 14.1KB/s 00:00
debug1: fd 0 clearing O_NONBLOCK
Transferred: sent 2152, received 1172 bytes, in 0.0 seconds
Bytes per second: sent 1391979.3, received 758085.4
debug1: Exit status 0