【问题标题】:Kubernetes Websockets API pod exec node.js client send methodKubernetes Websockets API pod exec node.js 客户端发送方法
【发布时间】:2017-12-12 21:25:20
【问题描述】:

我很难使用node.js websockets 客户端向交互式 bash shell 发送命令。我正在使用 kops 运行集群,并且能够与 pod 建立连接并获得提示,但我无法发送命令并接收响应。

所以我的连接看起来像:

const WebSocket = require('ws');
const fs = require('fs');
const readline = require('readline');
const unescape = require('querystring').unescape;
const escape = require('querystring').escape;

const channel = '0';
const access_token = "[the_api_token]";
const pod_name = 'nginx-726417742-s1nv2';
const host_address = 'wss://[the_api_url]';
const cmd = `${escape('/bin/bash')}&command=-i`;
const params = `stdout=1&stdin=1&stderr=1&tty=1&container=nginx&command=${cmd}`;
const url = `${host_address}/api/v1/namespaces/default/pods/${pod_name}/exec?${params}`;
const options = {
  headers: {
    'Authorization': `Bearer ${access_token}`
  },
  ca: fs.readFileSync('ca.crt'),
}
const ws = new WebSocket(url, options);
ws.on('open', () => {
  console.log('connected');
});
ws.on('message', (data, flags) => {
  process.stdout.write(data);
});
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});
rl.on('line', function (cmd) {
  const data = channel + cmd;
  if (ws && ws.readyState === 1) {
    ws.send(data);
  }
});

ws.on('message', (data, flags) 部分完美地打印了 shell 提示符root@nginx-726417742-s1nv2:/#,但随后我可以输入任何内容,它通过ws.send(data),但没有收到任何消息,也没有生成错误。我已经尝试将数据转换为 base64 并逐个字符发送而不是整行发送,但结果和行为始终相同。

如果我通过 kubectl proxy --disable-filter=true --port=8080 代理 API 并使用指向 ws://localhost:8080https://github.com/kubernetes-ui/container-terminal 并使用 /api/v1/namespaces/default/pods/${pod_name}/exec 我可以获得一个工作终端,但本地代理对我来说不是一个选项。

任何帮助将不胜感激。

【问题讨论】:

  • 嘿@Marcelo,你找到解决问题的方法了吗?

标签: node.js websocket kubernetes


【解决方案1】:

我知道我的回答来晚了。但也许我可以帮助其他人。我注意到,在使用 websocket 时,Kubernetes API 通常需要设置一个来源。否则 API 有时会返回奇怪的错误。在您的情况下,您可以尝试如下完成您的选项:

const options = {
  headers: {
    'Authorization': `Bearer ${access_token}`
  },
  ca: fs.readFileSync('ca.crt'),
  origin: 'https://<the_api_url>:<port>'
}

此外,我认为不需要将wss 设置为协议(在您的host_address 变量中)。通常在连接过程中协议会自动从https升级到wss

【讨论】:

    猜你喜欢
    • 2020-09-11
    • 2022-01-02
    • 1970-01-01
    • 2021-07-14
    • 2014-03-01
    • 2013-02-01
    • 2017-05-07
    • 1970-01-01
    • 2012-05-15
    相关资源
    最近更新 更多