感谢你的指导,你可以将exec.Command(command)
改为exec.Command("sh", "-c", command)
来在执行命令时添加”sh -c”参数。这样修改后的代码如下:
package main
import (
"fmt"
"io/ioutil"
"log"
"net"
"os/exec"
"golang.org/x/crypto/ssh"
)
func main() {
config := &ssh.ServerConfig{
PasswordCallback: func(c ssh.ConnMetadata, pass []byte) (*ssh.Permissions, error) {
if c.User() == "your_username" && string(pass) == "your_password" {
return nil, nil
}
return nil, fmt.Errorf("invalid username or password")
},
}
privateBytes, err := ioutil.ReadFile("private_key")
if err != nil {
log.Fatalf("Failed to load private key (%s)", err)
}
privateKey, err := ssh.ParsePrivateKey(privateBytes)
if err != nil {
log.Fatalf("Failed to parse private key (%s)", err)
}
config.AddHostKey(privateKey)
listener, err := net.Listen("tcp", "0.0.0.0:2222")
if err != nil {
log.Fatalf("Failed to listen for connections (%s)", err)
}
log.Println("Listening on 0.0.0.0:2222...")
for {
conn, err := listener.Accept()
if err != nil {
log.Printf("Failed to accept incoming connection (%s)", err)
continue
}
go handleConnection(conn, config)
}
}
func handleConnection(conn net.Conn, config *ssh.ServerConfig) {
defer conn.Close()
sConn, chans, reqs, err := ssh.NewServerConn(conn, config)
if err != nil {
log.Printf("Failed to handshake (%s)", err)
return
}
log.Printf("New SSH connection from %s", sConn.RemoteAddr())
go ssh.DiscardRequests(reqs)
for newChannel := range chans {
if newChannel.ChannelType() != "session" {
newChannel.Reject(ssh.UnknownChannelType, "unknown channel type")
continue
}
channel, requests, err := newChannel.Accept()
if err != nil {
log.Printf("Failed to accept channel (%s)", err)
return
}
go handleSession(channel, requests)
}
}
func handleSession(channel ssh.Channel, requests <-chan *ssh.Request) {
defer channel.Close()
for req := range requests {
switch req.Type {
case "exec":
// 处理执行命令的请求
command := string(req.Payload[4:])
log.Printf("Executing command: %s", command)
// 执行命令并将输出发送回客户端
output, err := exec.Command("sh", "-c", command).CombinedOutput()
if err != nil {
log.Printf("Command execution failed (%s)", err)
}
_, _ = channel.Write(output)
// 发送退出状态码给客户端
status := 0
_, _ = channel.SendRequest("exit-status", false, ssh.Marshal(&struct{ C uint32 }{uint32(status)}))
// 关闭通道
channel.Close()
case "pty-req":
// 处理终端请求(可选)
case "window-change":
// 处理窗口大小变化请求(可选)
default:
req.Reply(false, nil) // 不支持其他请求类型
}
}
}
请确保替换"your_username"
、"your_password"
和"private_key"
为正确的值,并将监听地址和端口调整为你需要的值。这段代码实现了一个简单的SSH服务器,可以接受来自客户端的连接并执行命令,将输出发送回客户端。
内容由零声教学AI助手提供,问题来源于学员提问