Ssh,login时运行命令,然后保持login?

我期待着这样做,但没有奏效:最后closures了连接。

我们可以通过ssh运行一个脚本,它将login到远程机器,运行一个命令,而不是断开?

所以在一台机器上ssh,cd到这样一个目录,然后运行一个命令,并保持login状态。

-Jonathan

(期待我使用)

#!/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 

添加一个; /bin/bash ; /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" 

🙂

如果你用Python来完成这个工作, 那么pexpect就有一个例子,它几乎完全符合你的要求:

 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. 

不要误解我的意思,我特别期待(特别是autoexpect),但是python对我来说更加容易。

ssh进入服务器的可能最简单最简单的方法是,在shell中生成一个交互的shell并运行命令,为bash创build一个自定义的rc文件。

在服务器上的自定义bashrc文件中,首先input默认文件,然后添加自定义命令,例如

〜/ .bashrc_custom:

 . ~/.bashrc cd dir/ workon virtualenvproject 

然后你可以像这样开始你的SSH会话:

 $ ssh -t server "/bin/bash --rcfile ~/.bashrc_custom -i" 

-t选项会强制执行一个伪tty分配,以便像tab-completion这样的工作。

--rcfile选项指定要加载哪个rcfile而不是缺省的rcfile。 重要提示:您必须在单字符选项之前在命令行上放置“double-dash arguments”才能被识别。

/ bin / bash的-i参数用于调用交互式shell。

如果有人想知道后台发生了什么,你应该看看sshd手册:

当用户成功login时,sshd执行以下操作:

  1. 如果login名在tty上,并且没有指定任何命令,则输出最后的login时间和/ etc / motd(除非在configuration文件或〜/ .hushlogin中禁止;请参阅FILES部分)。
  2. 如果login是在一个tty,logginglogin时间。
  3. 检查/ etc / nologin和/ var / run / nologin; 如果存在,则打印内容并退出(除非root)。
  4. 更改以正常的用户权限运行。
  5. build立基本的环境
  6. 读取文件〜/ .ssh / environment(如果存在),并允许用户更改其环境。 请参见sshd_config(5)中的PermitUserEnvironment选项。
  7. 更改用户的主目录。
  8. 如果存在〜/ .ssh / rc,则运行它; 否则,如果/ etc / ssh / sshrc存在,运行它; 否则运行xauth(1)。 标准input中给出了“rc”文件的X11authentication协议和cookie。 请参阅下面的SSHRC。
  9. 运行用户的shell 命令。

https://www.freebsd.org/cgi/man.cgi?sshd(8)#LOGIN_PROCESS

你通常应该避免以这种方式使用ssh,因为它打败了它的目的。
做一个

 ssh-add -l | grep "file_of_your_rsa_priv_key_here" 

以查看您的密钥是否在ssh活动会话池中列出,或者自己添加(使用ssh-add)。