user1299784
user1299784

Reputation: 2097

Expect ssh script (execute command on remote machine)

I'm writing an expect script that executes a command on a remote server using ssh.

Command syntax: ssh <classname> <command>

Code:

set ip "hive28.cs.berkeley.edu"
set class [lindex $argv 0]
// set $user and $ip according to class

set cmd [lindex $argv 1]
spawn ssh "$user\@$ip '$cmd'"
expect "assword"
send "$password\r";
interact

Unfortunately, I get this error:

~/foo> ssh2 162 'pwd'

spawn ssh ***@hive28.cs.berkeley.edu 'pwd'
ssh: Could not resolve hostname hive28.cs.berkeley.edu 'pwd': Name or service not known
send: spawn id exp6 not open
    while executing
"send "$password\r""
    invoked from within <...>

But when I run the generated command directly, it works (ignore the gdircolors warnings):

~/foo> ssh ***@hive28.cs.berkeley.edu 'pwd'
***@hive28.cs.berkeley.edu's password: 
/home/ff/cs162/adm/bashrc.d/70-gnu.sh: line 36: gdircolors: command not found
/home/cc/cs162/sp16/class/***

Upvotes: 1

Views: 1362

Answers (1)

Will
Will

Reputation: 24719

Try this instead:

set ip "hive28.cs.berkeley.edu"
set class [lindex $argv 0]

set cmd [lindex $argv 1]
spawn ssh "$user@$ip" "$cmd"
expect "assword"
send "$password\r";
interact

The problem seems to be with your quoting. "$user\@$ip" and "$cmd" are two separate arguments.

Upvotes: 1

Related Questions