如何以编程方式获取有状态的 ssh shell 会话?
我正在开发一个需要向远程服务器发送命令的应用程序。借助大量 SSH 客户端库,发送命令非常容易。
但是,我希望在每个命令之间保留 shell 状态(即当前工作目录、环境变量等)。我见过的所有客户端库都没有这样做。例如,以下是一个不执行我想要的操作的代码示例:
use Net::SSH::Perl;
my $server = Net::SSH::Perl->new($host);
$server->login($user, $pass);
$server->cmd('cd /var');
$server->cmd('pwd'); # I _would like_ this to output /var
发送命令之间还会执行其他任务,因此将诸如 $server->cmd( 'cd /var;)
是不可接受的。
I am working on an application that needs to send commands to remote servers. Sending commands is easy enough with the plethora of SSH client libraries.
However, I would like shell state (i.e. current working directory, environment variables, etc) preserved between each command. All client libraries that I have seen do not do this. For example, the following is an example of code that does not do what I want:
use Net::SSH::Perl;
my $server = Net::SSH::Perl->new($host);
$server->login($user, $pass);
$server->cmd('cd /var');
$server->cmd('pwd'); # I _would like_ this to output /var
There will be other tasks performed between sending commands, so combining the commands like $server->cmd('cd /var; pwd')
is not acceptable.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Net::SSH::Expect 可以满足您的需求“期望”方式并不完全可靠,因为它将解析命令的输出并尝试检测 shell 提示符何时再次出现。
Net::SSH::Expect does what you want, though the "Expect" way is not completely reliable as it will be parsing the output of your commands and trying to detect when the shell prompt appears again.
我不确定你到底在做什么,但你可以启动一个 SSH 会话。如果你真的不能做到这一点,也许你可以对所有内容使用绝对路径。
I'm not sure what you are doing exactly, but you could just start one SSH session. If you really can't do this, maybe you can just use absolute paths for everything.