![ssh + sudo + su 进入登录 shell](https://linux22.com/image/1439921/ssh%20%2B%20sudo%20%2B%20su%20%E8%BF%9B%E5%85%A5%E7%99%BB%E5%BD%95%20shell.png)
我有几台机器,我经常通过 ssh 连接,目的只是为了在sudo su
会话的剩余时间里以某些特殊用途用户的身份登录。一般工作流程如下:
mymachine:~ me$ ssh me@othermachine
othermachine:~ me$ sudo su - specialuser # note: no password needed
othermachine:~ specialuser$ # do stuff
我想将其归结为一行,以便我可以为其设置别名,这样我就可以为每台机器设置一个别名,并通过一个命令到达我需要的位置,而无需输入样板。我可能可以在登录时进行sudo su - specialuser
设置,但我想保持灵活性,以便根据需要进行操作。me@othermachine
sudo su
me
(笔记:我无法控制othermachine
其设置方式;这是我受聘时制定的工作流程。)
我的第一个想法就是
ssh me@othermachine "sudo su - specialuser"
这种方法是可行的,但是没有提示,而是^C
直接将它杀死并将我注销,而且我认为其他一些事情也可能出了问题。
看完之后使用完整登录 Shell 运行远程 ssh 命令我尝试了一些更奇特的东西,比如
ssh me@othermachine 'bash -l -c "sudo su - specialuser"'
和
ssh me@othermachine 'bash -l -c "sudo su - specialuser"; bash'
—— 我预计这两种方法都不会奏效,而且也没有奏效,但我认为我应该尝试一下,以确保完整性(并避免重复);它们产生了相同的无提示 shell(第二个 shell 增加了无提示的 after me
-ing shell,而exit
不是 for 的shell specialuser
)。我试过了
ssh me@othermachine "sudo su - specialuser -c bash -l"
但它只是让我
sudo: no tty present and no askpass program specified
有更好的想法吗?
答案1
这条线应该适合你
ssh -t me@machine "sudo su - specialuser"
此解决方案是否给我提示取决于-t
开关
ssh -t me@machine "/bin/bash -l" # Give me a prompt
ssh me@machine "/bin/bash -l" # Give me NO prompt
ssh me@machine # Give me NO prompt
注释man ssh
-t
强制分配伪终端。这可用于在远程机器上执行任意基于屏幕的程序,这非常有用,例如在实现菜单服务时。 多个 -t 选项强制分配 tty,即使 ssh 没有本地 tty。