首次提交

This commit is contained in:
2024-05-20 10:31:21 +08:00
commit af89dc9f6d
8 changed files with 7581 additions and 0 deletions
+8
View File
@@ -0,0 +1,8 @@
4eff13b0-dfa2-4dc5-9ed7-6853a3883c2c,eab6b02a9d8caf8a201e0fd25ed17eea7ab5d999c4c684674a686d8bad44ceea,1715746301
2533a032-379b-4ade-814b-d341994ada40,eab6b02a9d8caf8a201e0fd25ed17eea7ab5d999c4c684674a686d8bad44ceea,1715746313
708a7df2-3559-458e-bb17-62649aa25740,eab6b02a9d8caf8a201e0fd25ed17eea7ab5d999c4c684674a686d8bad44ceea,1715746329
e465aa83-713f-41b2-8829-7afcd8e7ee61,eab6b02a9d8caf8a201e0fd25ed17eea7ab5d999c4c684674a686d8bad44ceea,1715746349
e0516e08-b889-4c76-b6f0-fcf1fb7cdc23,eab6b02a9d8caf8a201e0fd25ed17eea7ab5d999c4c684674a686d8bad44ceea,1715748220
3190644d-e223-4557-994a-a4b2c711ef6f,eab6b02a9d8caf8a201e0fd25ed17eea7ab5d999c4c684674a686d8bad44ceea,1715748221
023bb1b2-f5e5-4524-a023-8491a89ca77a,ed4887928c617b433399df1fd6b03a9a4d3d92fd2ca4f235f693275a71d7b9e3,1715749182
519003fa-9e33-48d9-8c97-a672042c9be2,ed4887928c617b433399df1fd6b03a9a4d3d92fd2ca4f235f693275a71d7b9e3,1715749182
BIN
View File
Binary file not shown.
+8
View File
@@ -0,0 +1,8 @@
module github.com/aSemy/docker-exec-web-console
go 1.16
require (
github.com/davecgh/go-spew v1.1.1
golang.org/x/net v0.0.0-20210331212208-0fccb6fa2b5c
)
+11
View File
@@ -0,0 +1,11 @@
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/google/styleguide v0.0.0-20210329114118-635fe96f8ecd h1:tQYpGHa8IPfhWRxZX+3fm+fUvhUy5uuZZQ48bPsxxlU=
github.com/google/styleguide v0.0.0-20210329114118-635fe96f8ecd/go.mod h1:eCcidOd1xoE9GqhpLxRHZcv3rSJuAhgEm8Od+Zu2V2E=
golang.org/x/net v0.0.0-20210331212208-0fccb6fa2b5c h1:KHUzaHIpjWVlVVNh65G3hhuj3KB1HnjY6Cq5cTvRQT8=
golang.org/x/net v0.0.0-20210331212208-0fccb6fa2b5c/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
+123
View File
@@ -0,0 +1,123 @@
<html lang="en">
<head>
<link rel="stylesheet" href="xterm/xterm.css"/>
<script src="xterm/xterm.js"></script>
<style>
body {
padding: 0;
margin: 5px;
background-color: #000;
height: 100%;
}
#container-terminal {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
</style>
<title>Docker Exec Web Console</title>
</head>
<body>
<div id="container-terminal"></div>
<script type="text/javascript">
function resizeTerminal(term) {
const container = document.getElementById('container-terminal');
if (!container) {
console.error('Container element not found.');
return;
}
// 现在使用更精确的测量值,这些值应该基于你的终端设置
const style = window.getComputedStyle(container);
const charWidth = parseInt(style.getPropertyValue('--xterm-char-width'), 10) || 10;
const charHeight = parseInt(style.getPropertyValue('--xterm-char-height'), 10) || 20;
const width = container.offsetWidth;
const height = container.offsetHeight;
const cols = Math.floor(width / charWidth);
console.log(cols);
const rows = Math.floor(height / charHeight);
term.resize(cols, rows);
console.log(term);
}
function getQueryVar(variable) {
const query = window.location.search.substring(1);
const vars = query.split("&");
for (let i = 0; i < vars.length; i++) {
const pair = vars[i].split("=");
if (pair[0] === variable) {
return pair[1];
}
}
return false;
}
let token = getQueryVar('token');
if (!token) {
throw new Error('token not found');
}
let command = getQueryVar('cmd');
if (!command) {
command = '/bin/bash';
}
let websocket = new WebSocket(
"ws://"
+ window.location.hostname + ":"
+ window.location.port
+ window.location.pathname
+ "exec/"
+ token + ',' + window.btoa(command)
);
websocket.onopen = function () {
let term = new Terminal({
//cols: 300,
//rows: 30,
screenKeys: true,
useStyle: true,
cursorBlink: true,
});
term.on('data', function (data) {
websocket.send(data);
});
term.on('title', function (title) {
document.title = title;
});
term.open(document.getElementById('container-terminal'));
resizeTerminal(term);
window.addEventListener('resize', () => {
resizeTerminal(term);
});
websocket.onmessage = function (evt) {
term.write(evt.data);
}
websocket.onclose = function () {
term.write("Session terminated");
term.destroy();
}
websocket.onerror = function (evt) {
if (typeof console.log == "function") {
console.log(evt)
}
}
}
</script>
</body>
</html>
+203
View File
@@ -0,0 +1,203 @@
package main
import (
"bytes"
"encoding/base64"
"encoding/json"
"flag"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"net/http/httputil"
"os"
"strconv"
// "os"
"strings"
"time"
"github.com/davecgh/go-spew/spew"
"golang.org/x/net/websocket"
)
var port = flag.String("port", "6080", "port")
// var port = "6080"
var host = flag.String("host", "127.0.0.1:2735", "host")
var local_path = flag.String("local_path", "/root/apiserver/console_agent", "local_path")
var contextPath = "/"
func main() {
flag.Parse()
// if cp := os.Getenv("CONTEXT_PATH"); cp != "" {
contextPath = strings.TrimRight("/console", "/")
// }
http.Handle(contextPath+"/exec/", websocket.Handler(ExecContainer))
http_dir := http.FileServer(http.Dir(*local_path))
http.Handle(contextPath+"/", http_dir)
// 仅index.html
if err := http.ListenAndServe(":"+*port, nil); err != nil {
panic(err)
}
}
func getContainerIdByToken(token string) string {
// file, err := os.Open(".token")
token_file := *local_path + "/.token"
file, err := os.Open(token_file)
if err != nil {
return ""
}
// token文件格式 token,containerid,expire_at\n
// expire_at := time.Now().Unix()
defer file.Close()
buf := make([]byte, 1024)
for {
n, _ := file.Read(buf)
if 0 == n {
break
}
str := string(buf[:n])
lines := strings.Split(str, "\n")
for _, line := range lines {
if strings.Contains(line, token) {
data := strings.Split(line, ",")
expire_at := data[2]
expire_at_int, err := strconv.ParseInt(expire_at, 10, 64)
if err != nil {
return ""
}
// 是否过期
if expire_at_int < time.Now().Unix() {
continue
} else {
return data[1]
}
}
}
}
return ""
}
func ExecContainer(ws *websocket.Conn) {
wsParams := strings.Split(ws.Request().URL.Path[len(contextPath+"/exec/"):], ",")
token := wsParams[0]
container := getContainerIdByToken(token)
if container == "" {
print("connect container failed,token failed\n")
ws.Write([]byte("connect container failed,token failed"))
return
}
cmd, _ := base64.StdEncoding.DecodeString(wsParams[1])
type stuff struct {
Id string
}
var s stuff
params := bytes.NewBufferString("{\"AttachStdin\":true,\"AttachStdout\":true,\"AttachStderr\":true,\"Tty\":true,\"Cmd\":[\"" + string(cmd) + "\"]}")
resp, err := http.Post("http://"+*host+"/containers/"+container+"/exec", "application/json", params)
if err != nil {
panic(err)
}
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
panic(err)
}
json.Unmarshal([]byte(data), &s)
if err := hijack(*host, "POST", "/exec/"+s.Id+"/start", true, ws, ws, ws, nil, nil); err != nil {
panic(err)
}
fmt.Println("Connection!")
fmt.Println(ws)
spew.Dump(ws)
}
func hijack(addr, method, path string, setRawTerminal bool, in io.ReadCloser, stdout, stderr io.Writer, started chan io.Closer, data interface{}) error {
params := bytes.NewBufferString("{\"Detach\": false, \"Tty\": true}")
req, err := http.NewRequest(method, path, params)
if err != nil {
return err
}
req.Header.Set("User-Agent", "Docker-Client")
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Connection", "Upgrade")
req.Header.Set("Upgrade", "tcp")
req.Host = addr
dial, err := net.Dial("tcp", addr)
// When we set up a TCP connection for hijack, there could be long periods
// of inactivity (a long running command with no output) that in certain
// network setups may cause ECONNTIMEOUT, leaving the client in an unknown
// state. Setting TCP KeepAlive on the socket connection will prohibit
// ECONNTIMEOUT unless the socket connection truly is broken
if tcpConn, ok := dial.(*net.TCPConn); ok {
tcpConn.SetKeepAlive(true)
tcpConn.SetKeepAlivePeriod(30 * time.Second)
}
if err != nil {
return err
}
clientconn := httputil.NewClientConn(dial, nil)
defer clientconn.Close()
// Server hijacks the connection, error 'connection closed' expected
clientconn.Do(req)
rwc, br := clientconn.Hijack()
defer rwc.Close()
if started != nil {
started <- rwc
}
var receiveStdout chan error
if stdout != nil || stderr != nil {
go func() (err error) {
if setRawTerminal && stdout != nil {
_, err = io.Copy(stdout, br)
}
return err
}()
}
go func() error {
if in != nil {
io.Copy(rwc, in)
}
if conn, ok := rwc.(interface {
CloseWrite() error
}); ok {
if err := conn.CloseWrite(); err != nil {
}
}
return nil
}()
if stdout != nil || stderr != nil {
if err := <-receiveStdout; err != nil {
return err
}
}
spew.Dump(br)
go func() {
for {
fmt.Println(br)
spew.Dump(br)
}
}()
return nil
}
+2270
View File
File diff suppressed because it is too large Load Diff
+4958
View File
File diff suppressed because it is too large Load Diff