如何设置要在 ssh 别名中使用的“默认”用户名?

Kam*_*Cuk 0 bash ssh

我想设置一个别名,该别名将“默认”使用与我当前不同的用户名。像这样:

$ echo $USER          # outputs kamil
$ alias myssh='ssh -o User=somebody'   # non-working example of what I want to do
$ myssh server        # Uses somebody@server - all fine!
$ myssh root@server   # I want it to use root@server, but it does not. It connects to `somebody@server`!

# Easy testing:
$ myssh -v root@localhost |& grep -i 'Authenticating to'
debug1: Authenticating to localhost:22 as 'somebody'
#                                          ^^^^^^^^ - I want root!
Run Code Online (Sandbox Code Playgroud)

上面的代码不工作-在用户root@server覆盖-o User=somebody。我可以做一些事情:

myssh() {
   # parse all ssh arguments -o -F etc.
   if [[ ! "$server_to_connect_to" =~ @ ]]; then    # if the use is not specified
        # use a default username if not given
        server_to_connect_to="somebody@$server_to_connect_to"
   fi
   ssh "${opts[@]}" "$server_to_connect_to" "${rest_of_opts[@]}"
}
Run Code Online (Sandbox Code Playgroud)

但是需要解析函数中的所有 ssh 参数以提取服务器名称,然后向其中添加用户名。解决方案是修改~/.ssh/config和添加Host * User somebody- 但是我在一台没有主目录写访问权限的机器上(实际上根本没有主目录),我无法修改配置文件,我不想覆盖正常ssh操作反正。

是否有一个简单的解决方案来指定“默认可覆盖”用户无需修改即可连接到服务器~/.ssh/config

ter*_*don 5

不要使用别名,只需配置您的 ssh 客户端。编辑(或创建,如果它不存在)~/.ssh/config并添加这些行:

Host rootServer
HostName server_to_connect_to
User root

Host userServer
HostName server_to_connect_to
User somebody
Run Code Online (Sandbox Code Playgroud)

保存文件,您现在可以运行ssh rootServer以连接为rootssh userServer连接为somebody.