Home > OS >  How to hand over many commands into expect command?
How to hand over many commands into expect command?

Time:12-15

I have to connect with ssh to server and run a lot of commands. Solution as I know is script like this

expect -c 'spawn -noecho ssh '"admin"@"server"' "sudo bash -c \"command1\"";
      expect "*assword:*"; send "'${user_password}'\r";
      expect eof'

repeated several times. But I don't want to connect every time.

Maybe you know how to run command1 command2 ... in one connection?

Thank you

CodePudding user response:

From the man ssh, you can do

ssh [user@]hostname [command]

you can also pipe commands and use multiple commands like this:

ssh user@hostname "command1; command2; command3"

@SMA is also correct, you can create a script on your server and use:

ssh user@hostname 'bash myscript.sh'

CodePudding user response:

Expanding on @LittlePanic404's answer:

ssh user@hostname "command1; command2; command3"

can also be written with newlines, which is quite readable. Also, use the shell's quoted heredocs, and use the environment to pass shell variables into expect:

export user host password

expect << 'END_EXPECT'
    spawn -noecho ssh $env(user)@$env(host) {
        command1
        command2
        command3
    }
    expect "*assword:*" {send "$env(password)\r"}
    expect eof
END_EXPECT

Note that expect is an Tcl extension, and Tcl uses {braces} the same way the shell uses 'single quotes'

  • Related