package main
import (
"fmt"
"io"
"log"
"net"
"os"
"os/exec"
"runtime"
)
func main() {
if len(os.Args) != 3 {
_, err := fmt.Fprintf(os.Stderr, "Usage: %s <host> <port>\n", os.Args[0])
if err != nil {
log.Fatal(err)
}
return
}
// 开启监听
listener, err := net.Listen("tcp", os.Args[1]+":"+os.Args[2])
if err != nil {
log.Println("Failed to create listener:", err)
}
log.Println("Listening on " + os.Args[1] + ":" + os.Args[2])
defer func(listener net.Listener) {
err = listener.Close()
if err != nil {
log.Println("Failed to close listener:", err)
}
}(listener)
// 死循环 接收连接
for {
conn, err := listener.Accept()
if err != nil {
log.Println("Listener failed to accept:", err)
return
}
log.Printf("Addr : %v connected", conn.RemoteAddr())
// 开启 goroutine 处理conn
go handler(conn)
}
}
func handler(conn net.Conn) {
// 关闭conn
defer func(conn net.Conn) {
err := conn.Close()
if err != nil {
log.Println("Failed to close connection:", err)
}
}(conn)
r, w, err := os.Pipe() // 使用管道分离标准输出和标准错误
if err != nil {
log.Println("Failed to create pipe:", err)
return
}
defer func() {
if err := r.Close(); err != nil {
log.Println("Failed to close read pipe:", err)
}
if err := w.Close(); err != nil {
log.Println("Failed to close write pipe:", err)
}
}()
shell := ""
switch runtime.GOOS {
case "linux":
shell = "/bin/sh"
case "freebsd":
shell = "/bin/csh"
case "windows":
shell = "cmd.exe"
default:
shell = "/bin/sh"
}
cmd := exec.Command(shell)
cmd.Env = os.Environ()
cmd.Stdin = conn // 接收输入命令
cmd.Stdout = w // 执行命令的标准输出写入到管道
cmd.Stderr = conn // 执行命令的标准错误写入到连接
go func() {
if _, err := io.Copy(conn, r); err != nil { // 从管道读取数据写入到连接
log.Println("Failed to copy data to connection:", err)
}
}()
if err := cmd.Run(); err != nil { // 执行输入命令
log.Println("Command execution failed:", err)
}
}
go 采用tcp连接实现远程命令执行
最新推荐文章于 2024-08-29 08:59:25 发布