我尝试用 expect 来实现这个功能,但是没有用:它最后关闭了连接。
我们可以通过 ssh 运行一个脚本来登录远程机器,运行命令,并且不断开连接吗?
因此,在一台机器上通过 ssh 连接,cd 到某某目录,然后运行一个命令,并保持登录状态。
-乔纳森
(希望我用过)
#!/usr/bin/expect -f
set password [lrange $argv 0 0]
spawn ssh root@marlboro "cd /tmp; ls -altr | tail"
expect "?assword:*"
send -- "$password\r"
send -- "\r"
interact
答案1
; /bin/bash
在远程端的命令行末尾添加一个?即:
spawn ssh -t root@marlboro "cd /tmp; ls -altr | tail; /bin/bash -i"
更好的是,将 root 的 .bashrc 更改为如下形式:
PROMPT_COMMAND="cd /tmp && ls -altr | tail ; unset PROMPT_COMMAND"
:)
答案2
通过 ssh 进入服务器、生成交互式 shell 并在该 shell 内运行命令的最简单、最干净的方法可能是为 bash 创建自定义 rc 文件。
在服务器上的自定义 bashrc 文件中,首先获取默认文件,然后添加自定义命令,例如
〜/ .bashrc_自定义:
. ~/.bashrc
cd dir/
workon virtualenvproject
然后您可以像这样启动 SSH 会话:
$ ssh -t server "/bin/bash --rcfile ~/.bashrc_custom -i"
该-t
选项强制进行伪tty分配,以便制表符补全等功能能够正常工作。
该--rcfile
选项指定要加载哪个 rcfile,而不是默认的。重要提示:您必须在命令行上的单字符选项之前放置“双破折号参数”,以便被识别。
/bin/bash 的参数-i
用于调用交互式 shell。
答案3
如果你可以使用 Python 来实现这一点,期望有一个例子几乎完全按照你的要求做:
import pexpect
child = pexpect.spawn ('ftp ftp.openbsd.org')
child.expect ('Name .*: ')
child.sendline ('anonymous')
child.expect ('Password:')
child.sendline ('[email protected]')
child.expect ('ftp> ')
child.sendline ('ls /pub/OpenBSD/')
child.expect ('ftp> ')
print child.before # Print the result of the ls command.
child.interact() # Give control of the child to the user.
要使用 ssh 而不是 ftp 来执行此操作,您需要类似以下的代码(pexpect 中的示例文件有更多详细信息,但这里是基础知识):
import pexpect
child = pexpect.spawn ('ssh root@marlboro')
child.expect ('Password:')
child.sendline ('password')
child.expect ('prompt# ')
child.sendline ('cd /tmp')
child.expect ('prompt# ')
child.sendline ('ls -altr | tail')
child.expect ('prompt# ')
print child.before, child.after # Print the result of the ls command.
child.interact() # Give control of the child to the user.
别误会,我喜欢 expect(尤其是 autoexpect),但是 python 对我来说更容易理解。
答案4
如果你喜欢tmux
:
ssh -t user@host "cd /tmp; tmux a || tmux"
登录后,此命令始终cd /tmp
在远程主机上运行。然后,它会尝试连接到已在运行的会话,您可以在其中继续上次断开连接(通过依次键入 来模拟此操作)或分离(+ )tmux
后停止的地方工作,如果没有正在运行的会话,则它将启动一个新会话,这也会让您使用为该用户配置的 shell 保持登录状态。ssh
Enter ~ .tmux
Ctrlb dtmux
tmux