通過linux跳板ssh訪問容器

容器的IP是不固定的,因此無法像傳統服務器在ssh工具中配置清單;

最佳的方式是在瀏覽器上通過webterminal方案點擊鏈接直接打開ssh終端,要求開發像樣的容器管理平臺(我們的平臺還在設計階段。。。),另外webterminal訪問有一點點卡頓的感覺,沒有直接ssh暢快淋漓,因此通過linux跳板ssh訪問容器,是一個很有用的補充方案。

效果1

備註:project、app是pod的2個label,分別表示項目名稱(大類)和應用名稱(小類)

# ./ssh1.py 

==> porject:

seq   project     apps  pods
----- ---------- ----- -----
1     myproj1        2     5
2     myproj2        1     2

choose project seq : 1

==> apps:

seq   app          pods
----- ----------- -----
1     myproj1-inf    3
2     myproj1-www    2

choose app seq : 2

==> pods:

seq   name                           pod_ip          host_ip         age            restarts ready
----- ----------------------------- --------------- --------------- -------------- -------- -----
1     myproj1-www-5f64d878c8-2vq69    10.46.206.54    10.40.16.206    2d, 4:8:10     0        1    
2     myproj1-www-5f64d878c8-vbgxz    10.46.207.54    10.40.16.207    2d, 2:22:19    0        1    

choose pod seq : 2
[email protected]'s password: 
Last failed login: Wed Aug 21 09:52:57 CST 2019 from 10.40.16.220 on ssh:notty
There were 3 failed login attempts since the last successful login.
Last login: Wed Aug 21 09:44:31 2019 from 10.40.16.220
[appuser@myproj1-www-5f64d878c8-vbgxz ~]$ 

腳本1

# more ssh1.py 
#!/usr/bin/python3

from __future__ import print_function
import time,datetime,pytz
from kubernetes import client
from kubernetes.client.rest import ApiException
from pprint import pprint
import pandas
import os


apiToken = "your token"

configuration = client.Configuration()
configuration.host = "https://apiserver_ip:6443"
configuration.verify_ssl=True
configuration.debug = False
configuration.api_key = {"authorization": "Bearer " + apiToken}
configuration.ssl_ca_cert = "/root/.ca.crt"
myclient = client.ApiClient(configuration)

namespace = 'default'
pretty = 'true'
label_selector = ''
limit = 100
timeout_seconds = 100
watch = 'false'

## choose project

projlist = []
applist = []
v1 = client.CoreV1Api(myclient)
ret = v1.list_namespaced_pod(namespace, pretty=pretty, label_selector=label_selector, limit=limit, timeout_seconds=timeout_seconds, watch=watch)
for i in ret.items:
    projlist.append(i.metadata.labels['project'])
    applist.append(i.metadata.labels['app'])
projlist_uniq = list(set(projlist))
projlist_uniq.sort()
df = pandas.DataFrame({"project":projlist,"app":applist})
appnumdic = df.groupby(['project'])['app'].nunique().to_dict()
podnumdic = df.groupby(['project'])['app'].count().to_dict()

print()
print("==> porject:")
print()
print("{:<5} {:<10} {:>5} {:>5}".format('seq','project','apps','pods'))
print("----- ---------- ----- -----")
for i in range(len(projlist_uniq)):
    print("{:<5} {:<10} {:>5} {:>5}".format(i+1, projlist_uniq[i], appnumdic[projlist_uniq[i]], podnumdic[projlist_uniq[i]]))
print()
seqproj = input("choose project seq : ")
seqproj = seqproj.strip()
if seqproj.isdigit() and int(seqproj) <= len(projlist_uniq) and int(seqproj) >= 1:
    pass
else:
    print("Invalid sequence!!!")
    exit()

## choose app

label_selector = 'project=' + projlist_uniq[int(seqproj)-1]

projapplist = []
v1 = client.CoreV1Api(myclient)
ret = v1.list_namespaced_pod(namespace, pretty=pretty, label_selector=label_selector, limit=limit, timeout_seconds=timeout_seconds, watch=watch)
for i in ret.items:
    projapplist.append(i.metadata.labels['app'])
projapplist_uniq = list(set(projapplist))
projapplist_uniq.sort()
df = pandas.DataFrame({"app":projapplist})
appnumdic = df.groupby(['app'])['app'].count().to_dict()

print()
print("==> apps:")
print()
print("{:<5} {:<10} {:>5}".format('seq','app','pods'))
print("----- ---------- -----")
for i in range(len(projapplist_uniq)):
    print("{:<5} {:<10} {:>5}".format(i+1, projapplist_uniq[i], appnumdic[projapplist_uniq[i]]))
print()

seqapp = input("choose app seq : ")
seqapp = seqapp.strip()
if seqapp.isdigit() and int(seqapp) <= len(projapplist_uniq) and int(seqapp) >=1:
    pass
else:
    print("Invalid sequence!!!")
    exit()

## choose pod

label_selector = 'project=' + projlist_uniq[int(seqproj)-1] + ',app=' + projapplist_uniq[int(seqapp)-1]

ret = v1.list_namespaced_pod(namespace, pretty=pretty, label_selector=label_selector, limit=limit, timeout_seconds=timeout_seconds, watch=watch)
podlist = []
nowtime = datetime.datetime.now().replace(tzinfo=pytz.timezone('UTC')) - datetime.timedelta(hours=8)
for i in ret.items:
    delta = nowtime - i.metadata.creation_timestamp
    age=str(delta.days) + "d, " + str(delta.seconds%86400//3600) + ":" + str(delta.seconds%3600//60) + ":" + str(delta.seconds%60)
    poddetaildic = {}
    poddetaildic['name'] = i.metadata.name
    poddetaildic['pod_ip'] = i.status.pod_ip or "null"
    poddetaildic['host_ip'] = i.status.host_ip
    poddetaildic['age'] = age
    poddetaildic['restarts'] = i.status.container_statuses[0].restart_count
    poddetaildic['ready'] = i.status.container_statuses[0].ready
    podlist.append(poddetaildic)

print()
print("==> pods:")
print()
print("{:<5} {:<30} {:<15} {:<15} {:<14} {:<8} {:<5}".format('seq','name','pod_ip','host_ip','age','restarts','ready'))
print("----- ----------------------------- --------------- --------------- -------------- -------- -----")
for i in range(len(podlist)):
    print('{:<5} {:<30} {:<15} {:<15} {:<14} {:<8} {:<5}'.format(i+1,podlist[i]["name"],podlist[i]["pod_ip"],podlist[i]["host_ip"],podlist[i]["age"],podlist[i]["restarts"],podlist[i]["ready"])
)
print()

seqpod = input("choose pod seq : ")
seqpod = seqpod.strip()
if seqpod.isdigit() and int(seqpod) <= len(podlist) and int(seqpod) >=1:
    #print("You have choose:" + podlist[int(seqpod)-1]["pod_ip"])
    os.system("ssh appuser@" + podlist[int(seqpod)-1]["pod_ip"] + " -o 'StrictHostKeyChecking no'")
else:
    print("Invalid sequence!!!")
    exit()

如果上述效果嫌麻煩,記得appname的情況下,可以用下面更直接的方式。

效果2

# ./ssh2.py myproj1-www

==> pods:

seq   name                           pod_ip          host_ip         age            restarts ready
----- ----------------------------- --------------- --------------- -------------- -------- -----
1     myproj1-www-5f64d878c8-2vq69    10.46.206.54    10.40.16.206    2d, 4:59:51    0        1    
2     myproj1-www-5f64d878c8-vbgxz    10.46.207.54    10.40.16.207    2d, 3:14:0     0        1    

choose pod seq : 2
[email protected]'s password: 
Last login: Wed Aug 21 19:46:48 2019 from 10.40.16.220
[appuser@myproj1-www-5f64d878c8-vbgxz ~]$ 

腳本2(腳本1簡化即可)

# more ssh2.py 
#!/usr/bin/python3

from __future__ import print_function
import time,datetime,pytz
from kubernetes import client
from kubernetes.client.rest import ApiException
from pprint import pprint
import pandas
import os,sys

if len(sys.argv) != 2:
    print("Usage: " + sys.argv[0] + " [appname]")
    sys.exit(1)
else:
    appname = sys.argv[1]

apiToken = "your token"

configuration = client.Configuration()
configuration.host = "https://apiserver_ip:6443"
configuration.verify_ssl=True
configuration.debug = False
configuration.api_key = {"authorization": "Bearer " + apiToken}
configuration.ssl_ca_cert = "/root/.ca.crt"
myclient = client.ApiClient(configuration)

namespace = 'default'
pretty = 'true'
label_selector = ''
limit = 100
timeout_seconds = 100
watch = 'false'


label_selector = 'app=' + appname
v1 = client.CoreV1Api(myclient)
ret = v1.list_namespaced_pod(namespace, pretty=pretty, label_selector=label_selector, limit=limit, timeout_seconds=timeout_seconds, watch=watch)
if len(ret.items) == 0:
    print("no pod matched, check if '" + appname + "' is a valid appname!!!")
    exit()
podlist = []
nowtime = datetime.datetime.now().replace(tzinfo=pytz.timezone('UTC')) - datetime.timedelta(hours=8)
for i in ret.items:
    delta = nowtime - i.metadata.creation_timestamp
    age=str(delta.days) + "d, " + str(delta.seconds%86400//3600) + ":" + str(delta.seconds%3600//60) + ":" + str(delta.seconds%60)
    poddetaildic = {}
    poddetaildic['name'] = i.metadata.name
    poddetaildic['pod_ip'] = i.status.pod_ip or "null"
    poddetaildic['host_ip'] = i.status.host_ip
    poddetaildic['age'] = age
    poddetaildic['restarts'] = i.status.container_statuses[0].restart_count
    poddetaildic['ready'] = i.status.container_statuses[0].ready
    podlist.append(poddetaildic)

print()
print("==> pods:")
print()
print("{:<5} {:<30} {:<15} {:<15} {:<14} {:<8} {:<5}".format('seq','name','pod_ip','host_ip','age','restarts','ready'))
print("----- ----------------------------- --------------- --------------- -------------- -------- -----")
for i in range(len(podlist)):
    print('{:<5} {:<30} {:<15} {:<15} {:<14} {:<8} {:<5}'.format(i+1,podlist[i]["name"],podlist[i]["pod_ip"],podlist[i]["host_ip"],podlist[i]["age"],podlist[i]["restarts"],podlist[i]["ready"])
)
print()

seqpod = input("choose pod seq : ")
seqpod = seqpod.strip()
if seqpod.isdigit() and int(seqpod) <= len(podlist) and int(seqpod) >=1:
    os.system("ssh appuser@" + podlist[int(seqpod)-1]["pod_ip"] + " -o 'StrictHostKeyChecking no'")
else:
    print("Invalid sequence!!!")
    exit()

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章