33import sys
44import os
55from BaseServer import BaseServer
6+ import subprocess
67
78# 环境变量
9+ os .environ ["PATH" ] = "/usr/local/bin:/opt/homebrew/bin:" + os .environ .get ("PATH" , "" )
810separator = os .environ .get ("separator" , " | " )
9- sshDataFileName = os .environ .get ("SSH_DATA_FILE_NAME" , "data/ssh-data.json" )
11+ sshDataFileName = os .environ .get ("SSH_DATA_FILE_PATH" , "data/ssh-data.json" )
12+ TMUX_SESSION_NAME = os .environ .get ("TMUX_SESSION_NAME" , "" )
1013
1114class sshServer (BaseServer ):
1215 data = []
@@ -25,11 +28,63 @@ def __init__(self, serverDataFile):
2528 f"/usr/bin/expect { self .workFlowPath } /login.expect" ,
2629 ]
2730
31+ def has_tab_with_session_name (self , name_fragment ):
32+ """检查是否有标签页的会话名称包含指定字符串"""
33+
34+ applescript = f'''
35+ tell application "iTerm"
36+ if (count of windows) = 0 then
37+ return false
38+ end if
39+
40+ repeat with w in windows
41+ tell w
42+ repeat with aTab in tabs
43+ try
44+ if (name of current session of aTab) contains "{ name_fragment } " then
45+ return true
46+ end if
47+ on error
48+ -- 忽略错误
49+ end try
50+ end repeat
51+ end tell
52+ end repeat
53+
54+ return false
55+ end tell
56+ '''
57+
58+ try :
59+ result = subprocess .run (['osascript' , '-e' , applescript ],
60+ capture_output = True , text = True , timeout = 5 )
61+ output = result .stdout .strip ().lower ()
62+ return output == "true"
63+ except Exception as e :
64+ return False
65+
2866 def run (self , methodName , * args , ** kwargs ):
2967 method = getattr (self , methodName , None )
3068 if method and callable (method ):
31- result = method (* args , ** kwargs )
32- print (result , end = '' )
69+ name , result = method (* args , ** kwargs )
70+ if TMUX_SESSION_NAME and (methodName == "getByIndex" or methodName == "add" ):
71+ name = name .replace ("." , "_" )
72+ # check tmux session exist
73+ session_check = subprocess .run (["tmux" , "has-session" , "-t" , TMUX_SESSION_NAME ], capture_output = True )
74+ if session_check .returncode != 0 :
75+ # create tmux session
76+ subprocess .run (["tmux" , "new-session" , "-d" , "-s" , TMUX_SESSION_NAME ])
77+ # check tmux window exist
78+ window_check = subprocess .run (["tmux" , "list-windows" , "-t" , TMUX_SESSION_NAME , "-F" , "#{window_name}" ], capture_output = True , text = True )
79+ if name not in window_check .stdout .splitlines ():
80+ if self .has_tab_with_session_name (TMUX_SESSION_NAME ):
81+ print (f"tmux new-window -t { TMUX_SESSION_NAME } -n \" { name } \" && tmux send-keys -t { TMUX_SESSION_NAME } :{ name } \" { result } \" Enter && osascript -e 'tell application \" iTerm\" to tell current window to tell current tab to close' && osascript -e 'tell application \" iTerm\" ' -e 'tell current window' -e 'repeat with aTab in tabs' -e 'tell aTab' -e 'if (name of current session) contains \" { TMUX_SESSION_NAME } \" then' -e 'select aTab' -e 'exit repeat' -e 'end if' -e 'end tell' -e 'end repeat' -e 'end tell' -e 'end tell'" , end = '' )
82+ else :
83+ print (f"tmux new-window -t { TMUX_SESSION_NAME } -n \" { name } \" && tmux send-keys -t { TMUX_SESSION_NAME } :{ name } \" { result } \" Enter && tmux attach -t { TMUX_SESSION_NAME } " , end = '' )
84+ else :
85+ print (result , end = '' )
86+ else :
87+ print (result , end = '' )
3388 else :
3489 raise AttributeError (f"Method { methodName } not found" )
3590
@@ -55,7 +110,7 @@ def delete(self, keywordIndex):
55110 if 'rootpwd' in item :
56111 output .append (item ['rootpwd' ])
57112
58- return "\n " .join (output )
113+ return "" , " \n " .join (output )
59114 except IndexError :
60115 return 'Delete Failed! Server may be remove!'
61116
@@ -74,7 +129,7 @@ def copy(self, keywordIndex):
74129 if 'rootpwd' in item :
75130 output .append (item ['rootpwd' ])
76131
77- return "\n " .join (output )
132+ return "" , " \n " .join (output )
78133 except IndexError :
79134 return 'Copy Failed! Server may be remove!'
80135
@@ -131,7 +186,7 @@ def add(self, info, addLabel="add"):
131186 else :
132187 self .args .append (f"'{ item ['host' ]} '" )
133188
134- return " " .join (self .args )
189+ return item [ 'name' ], " " .join (self .args )
135190
136191 def get (self , keyword ):
137192 queryList = []
@@ -168,7 +223,7 @@ def get(self, keyword):
168223 item ['title' ] = 'Input <enter> to save.'
169224 item ['valid' ] = True
170225 queryList .append (item )
171- return json .dumps ({ 'items' : queryList })
226+ return "" , json .dumps ({ 'items' : queryList })
172227
173228 def getByIndex (self , keywordIndex ):
174229 keywordIndex = int (keywordIndex )
@@ -185,7 +240,7 @@ def getByIndex(self, keywordIndex):
185240 else :
186241 self .args .append (f"'{ item ['host' ]} '" )
187242
188- return " " .join (self .args )
243+ return item [ 'name' ], " " .join (self .args )
189244 except IndexError :
190245 return 'Execute Failed! Server may be remove!'
191246
0 commit comments