What I'm trying to do is write an expect script that will allow me to search for file A, and if file A is found then send a series of commands. If files B, or C are found then continue on through the script. I keep getting stuck on the regular expression. I run the expression through www.myregextester.com alone with the data I'm searching for and it matches up just fine. If anyone has any experience with this I would really appreciate the help.
send "term length 0\r"
expect "*#"
send "wr mem\r"
expect "*#"
send "dir flash:\r"
expect
if [[ \bc3750-ipservicesk9-mz.122-55.SE7.bin\b ]]; then {
send "conf t\r"
expect "*(config)#"
send "boot system flash:c3750-ipservicesk9-mz.122-55.SE7.bin\r"
expect "*(config)#"
send "exit\r"
expect "*#"
send "reload at 02:00 8 June\r"
expect "System configuration has been modified. Save? [yes/no]:"
send "yes\r"
expect "Proceed with reload? [confirm]"
send "\r"
expect "*#"
send "wr\r"
expect "*#"
send "exit\r
expect eof
elif [[ \bc3750-ipservicesk9-mz.122-55.SE5\b | b\c3750-ipservicesk9-mz.122-55.SE5.bin\b} ]]; then
fi
}
expect {
-re {\mc3750-ipservicesk9-mz\.122-55\.SE7\.bin\M} {
send "conf t\r"
#...
}
-re {\mc3750-ipservicesk9-mz\.122-55\.SE5(?:\.bin)?\M}
}
Expect is an extension of Tcl: you can read about Tcl regular expressions here.
Related
I am trying to create a script which will "send" input as per the output received from executing the previous script.
#!/usr/bin/expect --
set timeout 60
spawn ssh user#server1
expect "*assword*" { send "password\r"; }
expect "*$*" { send "./jboss.sh status \r"; }
if [ expect "*running*" ];
then { send "echo running \r"; }
else { send "./jboss.sh start \r"; }
fi
I am trying to do something like this, but I am stuck in the if else statement. How can I fix it?
You can simply group them into single expect statement and whichever matched, it can be processed accordingly.
#!/usr/bin/expect
set timeout 60
spawn ssh user#server1
expect "assword" { send "password\r"; }
# We escaped the `$` symbol with backslash to match literal '$'
# The last '$' sign is to represent end-of-line
set prompt "#|%|>|\\\$ $"
expect {
"(yes/no)" {send "yes\r";exp_continue}
"password:" {send "password\r";exp_continue}
-re $prompt
}
send "./jboss.sh status\r"
expect {
"running" {send "echo running\r"}
-re $prompt {send "./jboss.sh start \r"}
}
expect -re $prompt
I'm building a tool were a command with a password needs to be entered.
I want when I enter this command with the password, the command line replaces each character with "*" or " ", so the command and the password will not be observable !
is there such a command that tells the TCL interpreter "from this point, show each character entered as *", and then switch back to regular mode ?
any other suggestion will be valuable too.
In your case, you shall take "full control" over your terminal and disable its default echoing behavior (In UNIX the likes the terminal should be entered into the so-called raw mode)
Then, you can read the characters one-by-one (till max password size or till Enter is pressed) and echo '*' per each pressed character.
You got working code examples both on UNIX and Windows how doing so here
You may want reading also this link echo-free password entry TCL wiki
proc enableRaw {{channel stdin}} {
exec /bin/stty raw -echo <#$channel
}
proc disableRaw {{channel stdin}} {
exec /bin/stty -raw echo <#$channel
}
enableRaw
set c [read stdin 1]
puts -nonewline $c
disableRaw
package require twapi
proc enableRaw {{channel stdin}} {
set console_handle [twapi::GetStdHandle -10]
set oldmode [twapi::GetConsoleMode $console_handle]
set newmode [expr {$oldmode & ~6}] ;# Turn off the echo and line-editing bits
twapi::SetConsoleMode $console_handle $newmode
}
proc disableRaw {{channel stdin}} {
set console_handle [twapi::GetStdHandle -10]
set oldmode [twapi::GetConsoleMode $console_handle]
set newmode [expr {$oldmode | 6}] ;# Turn on the echo and line-editing bits
twapi::SetConsoleMode $console_handle $newmode
}
enableRaw
set c [read stdin 1]
puts -nonewline $c
disableRaw
(Assuming Linux.) By far the easiest way to handle passwords in a terminal is to turn off echoing of input but leave the terminal otherwise in cooked mode. It won't show a * for each entered character, but it does mean that you don't have to handle things like backspace (when a user realises they typed the last couple of characters wrong before hitting Return), etc.
exec /bin/stty -echo <#stdin
set password [gets stdin]
puts ""
exec /bin/stty echo <#stdin
If you've got Tcl 8.6, you can easily make this more robust with this procedure:
proc getPassword {{prompt "Password: "}} {
exec /bin/stty -echo <#stdin
try {
puts -nonewline $prompt
flush stdout
return [gets stdin]
} finally {
puts ""
flush stdout
exec /bin/stty echo <#stdin
}
}
(It's possible to use catch and some scripting to emulate try…finally but it's really annoying.)
If you have a GUI and prefer that, you make a password entry box by setting the -show option to something non-empty (e.g., * to show an asterisk).
Friends , im trying to automate a routing using expect , basically its a debug plugin in a special equipment that i need to log some data , to access this debug plugin my company needs to give me a responsekey based on a challengekey , its a lot of hosts and i need to deliver this by friday , what i've done so far.
#!/usr/bin/expect -f
match_max 10000
set f [open "cimc.txt"]
set hosts [split [read $f] "\n"]
close $f
foreach host $hosts {
spawn ssh ucs-local\\marcos#10.2.8.2
expect "Password: "
send "Temp1234\r"
expect "# "
send "connect cimc $host\r"
expect "# "
send "load debug plugin\r"
expect "ResponseKey#>"
sleep 2
set buffer $expect_out(buffer)
set fid [open output.txt w]
puts $fid $buffer
close $fid
sleep 10
spawn ./find-chag.sh
sleep 2
set b [open "key.txt"]
set challenge [read $b]
close $b
spawn ./find-rep.sh $challenge
sleep 3
set c [open "rep.txt"]
set response [read $c]
close $c
puts Response-IS
send "\r"
expect "ResponseKey#> "
send "$response"
}
$ cat find-chag.sh
cat output.txt | awk 'match($0,"ChallengeKey"){print substr($0,RSTART+15,38)}' > key.txt
$ cat find-rep.sh
curl bla-blabla.com/CIMC-key/generate?key=$1 | grep ResponseAuth | awk 'match($0,"</td><td>"){print substr($0,RSTART+9,35)}' > rep.txt
i dont know how to work with regexp on expect so i put the buffer output to a file and used bash script , the problem is that after i run the scripts with spawn looks like my ssh session is lost , does anyone have any tips? should i use something else instead of spawn to invoke my scripts?
expect -re "my tcl compatible regular expression goes here"
Should allow you to use regular expressions.
How do I get the output of an external command and extract values from it?
I have something like this:
stdin, stdout, stderr, wait_thr = Open3.popen3("#{path}/foobar", configfile)
if /exit 0/ =~ wait_thr.value.to_s
runlog.puts("Foobar exited normally.\n")
puts "Test completed."
someoutputvalue = stdout.read("TX.*\s+(\d+)\s+")
puts "Output value: " + someoutputvalue
end
I'm not using the right method on stdout since Ruby tells me it can't convert String into Integer.
So for instance, if the output is
"TX So and so: 28"
I would like to get only "28". I validated that the regex above matches what I need to match, I'm only wondering how to store that extracted value in a variable.
What is the right way of doing this? I can't find anywhere in the documentation the methods available for stdout. I'm using stout.read from Ruby 1.9.3.
All the information needed is in the Popen3 documentation, but you have to read it all and look at the examples pretty carefully. You can also glean useful information from the Process docs too.
Maybe this will 'splain it better:
require 'open3'
captured_stdout = ''
captured_stderr = ''
exit_status = Open3.popen3(ENV, 'date') {|stdin, stdout, stderr, wait_thr|
pid = wait_thr.pid # pid of the started process.
stdin.close
captured_stdout = stdout.read
captured_stderr = stderr.read
wait_thr.value # Process::Status object returned.
}
puts "STDOUT: " + captured_stdout
puts "STDERR: " + captured_stderr
puts "EXIT STATUS: " + (exit_status.success? ? 'succeeded' : 'failed')
Running that outputs:
STDOUT: Wed Jun 12 07:07:12 MST 2013
STDERR:
EXIT STATUS: succeeded
Things to note:
You often have to close the stdin stream. If the called application expects input on STDIN it will hang until it sees the stream close, then will continue its processing.
stdin, stdout, stderr are IO handles, so you have to read the IO class documentation to find out what methods are available.
You have to output to stdin using puts, print or write, and read or gets from stdout and stderr.
exit_status isn't a string, it's an instance of the Process::Status class. You can mess with trying to parse from its to_s version, but don't. Instead use the accessors to see what it returned.
I passed in the ENV hash, so the child program had access to the entire environment the parent saw. It's not necessary to do that; Instead you can create a reduced environment for the child if you don't want it to have access to everything, or you can mess with its view of the environment by changing values.
The code stdout.read("TX.*\s+(\d+)\s+") posted in the question is, um... nonsense. I have no idea where you got that as nothing like that is documented in Ruby's IO class for IO#read or IO.read.
It's easier to use capture3 if you don't need to write to STDIN of the called code:
require 'open3'
stdout, stderr, exit_status = Open3.capture3('date')
puts "STDOUT: " + stdout
puts "STDERR: " + stderr
puts "EXIT STATUS: " + (exit_status.success? ? 'succeeded' : 'failed')
Which outputs:
STDOUT: Wed Jun 12 07:23:23 MST 2013
STDERR:
EXIT STATUS: succeeded
Extracting a value from a string using a regular expression is trivial, and well covered by the Regexp documentation. Starting from the last code example:
stdout[/^\w+ (\w+ \d+) .+ (\d+)$/]
puts "Today is: " + [$1, $2].join(' ')
Which outputs:
Today is: Jun 12 2013
That's using the String.[] method which is extremely flexible.
An alternate is using "named captures":
/^\w+ (?<mon_day>\w+ \d+) .+ (?<year>\d+)$/ =~ stdout
puts "Today is: #{ mon_day } #{ year }"
which outputs the same thing. The downside to named captures is they're slower for what I consider a minor bit of convenience.
"TX So and so: 28"[/\d+$/]
=> "28"
I'd like to create a procmail recipe or Perl or shell script that will send an auto response to the original sender as well as anybody that was copied (either To: or cc:) on the original email.
Example:
bob#example.com writes an email to john#example.com and paul#example.com (in the To: field). Copies are sent via cc: to rob#example.com and alice#example.com.
I'd like the script to send an auto response to the original sender (bob#example.com) and everybody else that was sent a copy of the email (john#example.com, paul#example.com, rob#example.com and alice#example.com).
Thanks
You should be able to accomplish this using the this procmail module for Perl 5. You could also just use the procmail configuration files to do this as well.
Here's an example of our procmail configuration sending e-mails "through" a perl script.
:0fw
* < 500000
| /etc/smrsh/decode_subject.pl
I hope that helps get ya started.
FROM=`formail -rtzxTo:`
CC=`formail -zxTo: -zxCc: | tr '\n' ,`
:0c
| ( echo To: "$FROM"; echo Cc: "$CC"; echo Subject: auto-reply; \
echo; echo Please ignore. ) \
| $SENDMAIL -oi -t
A well-formed auto-reply should set some additional headers etc; but this should hopefully be enough to get you started. See also http://porkmail.org/era/mail/autoresponder-faq.html
Depending on you flavor of tr you might need to encode the newline differently; not all implementations of tr understand the '\n' format. Try with '\012' or a literal newline in single quotes if you cannot get this to work.