How to let Kubernetes pod run a local script

2/3/2021

I want to run a local script within Kubernetes pod and then set the output result to a linux variable

Here is what I tried:

# if I directly run -c "netstat -pnt |grep ssh", I get output assigned to $result:

cat check_tcp_conn.sh 
#!/bin/bash
result=$(kubectl exec -ti <pod_name> -- /bin/bash -c "netstat -pnt |grep ssh")
echo "result is $result"

What I want is something like this:

#script to be called:
cat netstat_tcp_conn.sh
#!/bin/bash
netstat -pnt |grep ssh

#script to call netstat_tcp_conn.sh:
cat check_tcp_conn.sh 
#!/bin/bash
result=$(kubectl exec -ti <pod_name> -- 
/bin/bash -c "./netstat_tcp_conn.sh)
echo "result is $result

the result showed result is /bin/bash: ./netstat_tcp_conn.sh: No such file or directory.

How can I let Kubernetes pod execute netstat_tcp_conn.sh which is at my local machine?

-- user389955
bash
kubernetes

2 Answers

2/3/2021

You can use following command to execute your script in your pod:

kubectl exec POD -- /bin/sh -c "`cat netstat_tcp_conn.sh`"
-- Ali Tou
Source: StackOverflow

2/3/2021

You can copy local files into pod using kubectl command like kubectl cp /tmp/foo <pod-name>:/tmp/
Then you can change its permission and make it executable and run it using kubectl exec.

-- Rushikesh
Source: StackOverflow