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

前端 未结 7 1416
南方客
南方客 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: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.

提交回复
热议问题