How to execute command in a pod (kubernetes) using API?

佐手、 提交于 2019-12-01 16:58:56

You'll probably have the best time using the Kubernetes client library, which is the same code the Kubectl uses, but if for some reason that isn't an option, than my best suggestion is to look through the client library's code for executing remote commands and seeing what headers it sets.

Use websocket client it's work.

In my local kuberenetes cluster, the connection metadata like this:

ApiServer = "172.21.1.11:8080"
Namespace = "default"
PodName = "my-nginx-3855515330-l1uqk"
ContainerName = "my-nginx"
Commands = "/bin/bash"

the connect url:

"ws://172.21.1.11:8080/api/v1/namespaces/default/pods/my-nginx-3855515330-l1uqk/exec?container=my-nginx&stdin=1&stdout=1&stderr=1&tty=1&command=%2Fbin%2Fbash"

On maxos, a wsclient CLI tool: wscat, you can use it as a test tool:

You can access the websocket example: "https://github.com/lth2015/container-terminal"

You can using a websocket client to exec into a pod, a quick demo.

javascript code shows how to connect to kubernetes:

<script type="text/javascript">
    angular.module('exampleApp', ['kubernetesUI'])
        .config(function(kubernetesContainerSocketProvider) {
            kubernetesContainerSocketProvider.WebSocketFactory = "CustomWebSockets";
        })
        .run(function($rootScope) {
            $rootScope.baseUrl = "ws://localhost:8080";
            $rootScope.selfLink = "/api/v1/namespaces/default/pods/my-nginx-3855515330-l1uqk";
            $rootScope.containerName = "my-nginx";
            $rootScope.accessToken = "";
            $rootScope.preventSocket = true;
        })
        /* Our custom WebSocket factory adapts the url */
        .factory("CustomWebSockets", function($rootScope) {
            return function CustomWebSocket(url, protocols) {
                url = $rootScope.baseUrl + url;
                if ($rootScope.accessToken)
                    url += "&access_token=" + $rootScope.accessToken;
                return new WebSocket(url, protocols);
            };
        });
</script>

you can test it in other language.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!