如何以编程方式获取有状态的 ssh shell 会话?

发布于 2024-11-25 10:47:11 字数 457 浏览 1 评论 0原文

我正在开发一个需要向远程服务器发送命令的应用程序。借助大量 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

唱一曲作罢 2024-12-02 10:47:11

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.

你げ笑在眉眼 2024-12-02 10:47:11

我不确定你到底在做什么,但你可以启动一个 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文