为什么要这样?
windows terminal可以说是win环境下最好用的终端仿真程序了,丰富的主题,使用GPU加速,完美兼容power shell的各种特性,并且可以通过编辑settings.json来获得灵活的自定义体验。
配合ohmyposh主题,养眼又好用
问题
我平时有多开虚拟机的需求,电脑上hyper-v、vmware、docker、wsl全装了,一部分是开发环境,另一些是网安玩的靶场,经常在多个虚拟机界面切换是很麻烦的,于是了解的小伙伴们都知道,我们平时更多是用xshell、finnalShell等ssh软件连接使用。于是有一天我突发奇想,既然wt的功能如此强大了,为啥非要用其他的远程软件呢?于是就萌发了在wt 中配置ssh的想法
大概想要实现的效果,每个标签都是ssh连接到对应系统
然而当我想要着手实现这个功能时,wt的配置文件似乎有些不够用了:
抛开微软在json里负责外观的键值,剩下最关键的一条无非是这句
"commandline": "C:\\Program Files\\PowerShell\\7\\pwsh.exe -nologo -NoExit"
通过 pwsh.exe --help 指令,我们可以看到有一个 -Command参数是用来执行命令的
Executes the specified commands (and any parameters) as though they
were typed at the PowerShell command prompt, and then exits, unless
the NoExit parameter is specified.
于是我尝试直接在后面跟上 "-Command 'ssh kali@192.168.2.2 ’ " 之类的参数,发现这样是不行的。终端只能打印出这句话,即使跟上&运行符号也没用。正当一筹莫展时,后面这句给了我灵感:
The Command parameter only accepts a script block for execution when
it can recognize the value passed to Command as a ScriptBlock type.
也就是说powshell内置的cmdlet、function 等等是可以执行的!于是我立马想到ohmyposh插件就是提前在全局文件里定义并加载主题的(这就是为什么装了美化后打开会有启动延迟…)于是通过这个线索,我就找到了所谓的全局配置文件
PowerShell 配置文件是在 PowerShell 启动时运行的脚本。 可以使用配置文件作为启动脚本来自定义环境。 可以添加命令、别名、函数、变量、模块、PowerShell 驱动器等。 还可以将其他特定于会话的元素添加到配置文件中,以便在每个会话中都可用,而无需导入或重新创建。
参考 http://防和谐learn.microsoft.com/zh-cn/powershell/module/Microsoft.PowerShell.Core/about/about_profiles?view=powershell-5.1
虽然有点复杂,但里面说的很清楚。总而言之我们就找到了$PROFILE这个关键角色,然后各位就可以脑洞大开地编辑自己想要的函数功能咯~
方案
我的一种拙劣的实现,可以参考 ORZ
# ------ My function BEGIN ------ #
function Use-ConfigDeafult {
param (
$StartValue
)
switch ($StartValue) {
1 {
oh-my-posh init pwsh --config "$env:POSH_THEMES_PATH\catppuccin.omp.json" | Invoke-Expression
Import-Module posh-git
# 引入 ps-read-line
Import-Module PSReadLine
# 设置预测文本来源为历史记录
Set-PSReadLineOption -PredictionSource History
# 每次回溯输入历史,光标定位于输入内容末尾
Set-PSReadLineOption -HistorySearchCursorMovesToEnd
# 设置 Tab 为菜单补全和 Intellisense
Set-PSReadLineKeyHandler -Key "Tab" -Function MenuComplete
# 设置 Ctrl+d 为退出 PowerShell
Set-PSReadlineKeyHandler -Key "Ctrl+d" -Function ViExit
}
2 {
#去掉oh-my-posh,加快速度
Invoke-Expression (&starship init powershell)
#ssh连接虚拟机
$cmd = "ssh kali@192.168.2.2"
Import-Module PSReadLine
Set-PSReadLineOption -PredictionSource History
Set-PSReadLineKeyHandler -Key "Tab" -Function MenuComplete
Invoke-Expression ($cmd)
}
Default {}
# ------ Set Hot-keys END ------ #
}
}
像我这样搞一下后,就可以用-Command参数运行任何想要的函数了
"commandline": "C:\\Program Files\\PowerShell\\7\\pwsh.exe -nologo -NoExit -Command Use-ConfigDeafult(1)"
作者:登上明星 B站:a_Walk_in_Cyber