Monday, April 29, 2024
 Popular · Latest · Hot · Upcoming
9
rated 0 times [  9] [ 0]  / answers: 1 / hits: 77474  / 2 Years ago, mon, october 17, 2022, 10:29:43

Can anybody let me know how to execute sudo commands with expect? I tried the following but this is not working. Can anyone give me suggestion please?



set login "sasuke"
set addr "hostname"
set pw "mypasswd"
spawn ssh $login@$addr
expect "$login@$addr's password:"
send "$pw
"
expect "#"
send "output=$(sudo virsh list --all | awk "/running/{print $2}" | tail -2); sudo virsh dominfo $output"
expect "password:"
send "$pw
"
expect "#"


When I tried the below script, it executed without errors, but I didn't get the output. Here is the script and the output when it executes. Where am I making a mistake here?



set login "sasuke"
set addr "hostname"
set pw "mypasswd"
spawn ssh $login@$addr
expect "$login@$addr's password:"
send "$pw
"
expect "#"
send {output=$(sudo virsh list --all | awk '/running/{print $2}' | tail -2)}
expect {
password: {send "$pw
"; exp_continue}
"#"
}
send {sudo virsh dominfo "$output"} ;# don't know if you need quotes there
expect {
password: {send "$pw
"; exp_continue}
"#"
}


Execution



sasuke@njob:~$ ./hypr.sh 
spawn ssh sasuke@hostname
sasuke@hostname's password:
sasuke@hostname:~$ output=$(sudo virsh list --all | awk '/running/{print $2}' | tail -10)sudo virsh dominfo '$output' sasuke@njob:~$

More From » bash

 Answers
5
set login "sasuke"
set addr "hostname"
set pw "mypasswd"
spawn ssh $login@$addr
expect "$login@$addr's password:"
send "$pw
"
expect "#"
send {output=$(sudo virsh list --all | awk '/running/{print $2}' | tail -2)}
expect {
password: {send "$pw
"; exp_continue}
"#"
}
send {sudo virsh dominfo "$output"} ;# don't know if you need quotes there
expect {
password: {send "$pw
"; exp_continue}
"#"
}


In Tcl (and, by extension, expect), curly braces act like the shell's single quotes: inhibit variable expansion.



The multi-pattern form of expect is useful for the case where you may not see a pattern. The exp_continue statement essentially "loops" within the expect so you can send the password and continue to expect the prompt. Since there is no action associated with the prompt pattern, control passes from the expect command to the next one.



I would recommend you save this as a separate script. First line should be



#!/usr/bin/expect -f


If you want to embed in a shell script:



#!/bin/sh
expect <<'END'
# code as above
END


Note the quotes around the first "END" -- that has the effect of single quoting the entire here-document so you don't have to worry about the shell interpreting the Expect variables


[#30770] Monday, October 17, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
itteast

Total Points: 291
Total Questions: 123
Total Answers: 104

Location: Tuvalu
Member since Wed, Mar 29, 2023
1 Year ago
;