How can i execute 2 or more commands in the same ssh session?

前端 未结 7 1345
南方客
南方客 2021-01-06 01:14

I have the following script:

#!/usr/bin/env ruby
require \'rubygems\'
require \'net/ssh\'

Net::SSH.start(\'host1\', \'root\', :password => \"mypassword1\         


        
相关标签:
7条回答
  • 2021-01-06 01:33

    You can just give different commands separated by a new line. Something like:

    @result = ssh.exec!("cd /var/example/engines/
                        pwd
                       ")
    puts @result
    

    Its probably easier (and clearer) to pass the command to a variable, then pass the variable into exec. Same principle though.

    0 讨论(0)
  • 2021-01-06 01:35

    see if there's something analogous to the file(utils?) cd block syntax, otherwise just run the command in the same subshell, e.g. ssh.exec "cd /var/example/engines/; pwd" ?

    0 讨论(0)
  • 2021-01-06 01:38
    ssh.exec("cd /var/example/engines/; pwd")
    

    That will execute the cd command, then the pwd command in the new directory.

    I'm not a ruby guy, but I'm going to guess there are probably more elegant solutions.

    0 讨论(0)
  • 2021-01-06 01:39

    Im not a ruby programmer, but you could try to concatenate your commands with ; or &&

    0 讨论(0)
  • 2021-01-06 01:50

    The current location of net-ssh-shell is changed.

    What I decided to use though to call a random shell script is to scp a file to the remote machine and source it into shell. Basically doing this: File.write(script_path, script_str) gear.ssh.scp_to(script_path, File.dirname(script_path)) gear.ssh.exec(". script_path")

    0 讨论(0)
  • 2021-01-06 01:53

    In Net::SSH, #exec & #exec! are the same, e.g. they execute a command (with the exceptions that exec! blocks other calls until it's done). The key thing to remember is that Net::SSH essentially runs every command from the user's directory when using exec/exec!. So, in your code, you are running cd /some/path from the /root directory and then pwd - again from the /root directory.

    The simplest way I know how to run multiple commands in sequence is to chain them together with && (as mentioned above by other posters). So, it would look something like this:

    #!/usr/bin/env ruby
    require 'rubygems'
    require 'net/ssh'
    
    Net::SSH.start('host1', 'root', :password => "mypassword1") do |ssh|
        stdout = ""
    
        ssh.exec!( "cd /var/example/engines/ && pwd" ) do |channel, stream, data|
            stdout << data if stream == :stdout
        end
        puts stdout
    
        ssh.loop
    end
    

    Unfortunately, the Net::SSH shell service was removed in version 2.

    0 讨论(0)
提交回复
热议问题