打开终端并从自动化程序运行一个命令以打开两个标签页并运行一个命令。

7

我想要做的是运行一个自动化脚本。脚本会打开终端并打开两个选项卡,每个选项卡会分别ssh到root@192.168.0.1和root@192.168.0.2,您会如何实现这一点?

2个回答

10

您可以使用 运行 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命令的结果存储在变量中——它将是对创建的终端的引用,您可以使用它与do script命令的in参数一起使用,以向该终端发送更多命令。


4

补充Chris Page的有用回答:

如果您希望两个终端选项卡位于同一个窗口中,情况会变得棘手:终端的AppleScript API长期以来存在一个限制,即无法在现有窗口中以编程方式创建新选项卡。

您可以通过GUI脚本解决问题;虽然以下处理程序makeNewTab()相当健壮,但它需要事先一次性授权辅助访问 - 请参见下面处理程序的注释。

请注意,授权Terminal.app和Automator.app等通用执行环境进行辅助访问意味着任何由它们运行的脚本都将具有这些特权。

如果您想更好地控制选项卡创建过程,例如能够分配特定配置文件(外观和行为设置)的能力,请查看我的答案,并在本答案底部应用它。

(*
  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

如果您愿意安装我的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 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接