【发布时间】:2016-02-14 20:37:35
【问题描述】:
我想做的是运行一个自动化脚本。发生的情况是它打开带有两个选项卡的终端,每个选项卡和 ssh 到 root@192.168.0.1 和 root@ssh@192.168.0.2;你会怎么做?
【问题讨论】:
我想做的是运行一个自动化脚本。发生的情况是它打开带有两个选项卡的终端,每个选项卡和 ssh 到 root@192.168.0.1 和 root@ssh@192.168.0.2;你会怎么做?
【问题讨论】:
您可以使用 Run AppleScript 操作来运行如下脚本:
on run {input, parameters}
tell application "Terminal"
activate
do script "ssh root@192.168.0.1"
do script "ssh root@192.168.0.2"
end tell
return input
end run
终端的do script 命令创建一个新的终端窗口并将给定的命令字符串发送到shell。请注意,如果您想向同一终端发送其他命令,请将do script 命令的结果存储在一个变量中——它将是对已创建终端的引用,您可以将其与in 参数一起使用do script 命令向该终端发送更多命令。
【讨论】:
补充Chris Page's helpful answer:
如果您希望两个终端选项卡都在相同窗口中,事情就会变得棘手:终端的 AppleScript API 的长期限制是无法以编程方式创建现有窗口中的新标签。
您可以使用 GUI 脚本解决该问题;虽然以下处理程序makeNewTab() 相当健壮,但它需要事先一次性授权才能进行辅助访问 - 请参阅下面处理程序上的 cmets。
请注意,授权通用执行环境(如 Terminal.app 和 Automator.app)进行辅助访问意味着它们运行的任何脚本都将拥有这些权限。
如果您希望对选项卡创建过程进行更多控制,例如分配特定配置文件(外观和行为设置)的能力,请参阅my answer here,以及此答案底部的应用程序。
(*
Creates a new tab in Terminal's front window and optionally executes a shell command,
if <shellCmdToRun> is a nonempty string.
Note:
* This handler effectively clicks the menu item that creates a new tab and
therefore requires assistive access:
The application running this handler - e.g., Terminal.app, Script Editor.app,
or Automator.app - must be added to the list at
System Preferences > Security & Privacy > Privacy > Accessibility,
using admin credentials.
* This handler activates Terminal first, which is required for it to work.
Caveat:
If there's no front window or if all windows are currently minimized, the
tab is created in a *new* window.
Examples:
my makeNewTab("") # open new tab (without executing a command)
my makeNewTab("ls") # open new tab and execute shell command `ls`
*)
on makeNewTab(shellCmdToRun)
tell application "Terminal"
# Note: If Terminal is not frontmost, clicking the new-tab menu item invariably
# creates the tab in a *new* window.
activate
# Find the File menu by position and click the menu item whose keyboard shortcut is
# ⌘T - this should work with any display language.
tell application "System Events" to ¬
tell menu 1 of menu item 2 of menu 1 of menu bar item 3 of menu bar 1 ¬
of application process "Terminal" to click (the first menu item ¬
whose value of attribute "AXMenuItemCmdChar" is "T" and ¬
value of attribute "AXMenuItemCmdModifiers" is 0)
# If specified, run a shell command in the new tab.
if shellCmdToRun ≠ missing value and shellCmdToRun ≠ "" then
do script shellCmdToRun as text in selected tab of front window
end if
end tell
end makeNewTab
如果您愿意安装 my ttab CLI,您可以完全不使用 AppleScript,而是从 Run Shell Script Automator 操作中运行以下命令:
# Create tab in new window (-w) and run specified command.
ttab -w ssh root@192.168.0.1
# Create additional tab in same window, with specific settings.
ttab -s Grass ssh root@192.168.0.2
【讨论】: