Unix 命令在服务器上有效,但在 ruby​​ ssh 会话中无效 [英] Unix commands work on server but not in ruby ssh session

查看:40
本文介绍了Unix 命令在服务器上有效,但在 ruby​​ ssh 会话中无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习如何将 net-ssh gem 用于 ruby​​.我想在登录目录 -/home/james 后执行以下命令.

I am trying to learn how to use the net-ssh gem for ruby. I want to execute the commands below, after I login to the directory - /home/james.

cd /
pwd
ls

当我使用腻子执行此操作时,它可以工作并且我可以看到目录列表.但是,当我使用 ruby​​ 代码执行此操作时,它不会给我相同的输出.

When I do this with putty, it works and i can see a list of directories. But, when I do it with ruby code, it does not give me the the same output.

require 'rubygems' 
require 'net/ssh'

host = 'server'
user = 'james'
pass = 'password123'

def get_ssh(host, user, pass)
    ssh = nil
    begin
        ssh = Net::SSH.start(host, user, :password => pass)
        puts "conn successful!"
    rescue
        puts "error - cannot connect to host"
    end
    return ssh
end

conn = get_ssh(host, user, pass)

def exec(linux_code, conn)
    puts linux_code
    result = conn.exec!(linux_code)
    puts result
end

exec('cd /', conn)
exec('pwd', conn)
exec('ls', conn)

conn.close

输出 -

conn successful!
cd /
nil
pwd
/home/james
ls
nil

我期待密码给我/而不是/home/james.这就是它在腻子中的工作方式.ruby 代码中的错误是什么?

I was expecting pwd to give me / instead of /home/james. That is how it works in putty. What is the mistake in the ruby code?

推荐答案

似乎每个命令都在它自己的环境中运行,所以当前目录不会从 exec 转移到 exec.如果您这样做,您可以验证这一点:

It seems like every command runs on it's own environment, so the current directory is not carried over exec to exec. You can verify this if you do:

exec('cd/&& pwd', conn)

它将打印/.文档中不清楚如何让所有命令在同一环境中执行,或者这是否可能.

It will print /. It is not clear from the documentation how to make all the commands execute on the same environment or if this is even possible at all.

这篇关于Unix 命令在服务器上有效,但在 ruby​​ ssh 会话中无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆