parse expect_output in a variable : TCL Data Structure

Sometimes we have to automate our steps through expect, run some commands in remote machine and capture the output of a command in a variable and use that variable in some other task.

So here is an example, how we can do that. The output from expect is always captured in expect_output(buffer) and we have to parse this to get our expected result.

So first we have store this expect_output(buffer) in a variable and which will have multiple lines along with our expected result.

Now we have to split that variable with "\n" as delimiter , which will create an array with all the lines in it.

Again from that array we can use indexing to extract the result from a certain position.

Here is one example.

[code lang=’bash’]
#!/usr/bin/expect
set password somepass
set cmd “ls -Art /var/lib/docker/path_to_files/ | tail -n 1”

spawn ssh root@10.59.1.150
set prompt “#|%|>|\\\$ $”
expect {
“(yes/no)” {send “yes\r”;exp_continue}
“password: ” {send “$password\r”;exp_continue}
-re $prompt
}
send “$cmd\r”
expect “# ”

set outcome [split $expect_out(buffer) “\n”]
set filename [lindex $outcome 1]

expect eof
puts “##########################”
puts $filename
puts “##########################”
[/code]

Add time stamp to commands in linux history

Some times we need to know at what time someone executed a command. We can add the time stamp to the commands displayed in the history.

echo 'export HISTTIMEFORMAT="%d/%m/%y %T "' >> ~/.bash_profile ; source ~/.bash_profile

Then type history command and it will display the commands executed with their timestamp. e.g.

873 18/05/16 05:18:05 docker pull ubuntu
874 18/05/16 05:18:05 docker images
875 18/05/16 05:18:05 docker tag ubuntu:latest slcn09vmf0022.us.oracle.com:/5000
876 18/05/16 05:18:05 docker ps
877 18/05/16 05:18:05 docker stop bkdevregistry
878 18/05/16 05:18:05 dockedr rm bkdevregistry

 

String manipulation tricks in bash

  • In some cases we have to modify the strings in a bash variable. Lets say : There are many files inside $(pwd)  with name as  a_ver10, b_ver10, c_ver10. We have to modify them back to a,b,c respectively. This below bash one liner can help to achieve this.
  • Inside the directory run this below command.

 

for file in $(ls -1d *_ver10); do mv $file  ${file%_ver10}; done

Moving some files into another dir or deleting them(change mv to rm).

for file in $(ls -1d *_ver11); do mv ${file%_ver11} bkp/ ;done

 

Creating simple progress bar in shell / Python

Progressbar indicates if certain tasks are getting executed and when they completed.

In bash oneliner:

printf “Starting [“;for num in $(seq 50);do printf “#”;sleep 0.5;done;printf “] Successfull”

In Python:

sys.stdout.write(“Starting Operation[“)
for d in range(60):

sys.stdout.write(‘#’)
sys.stdout.flush()
time.sleep(0.50)

sys.stdout.write(“]Stoping Operation”)

These can be modified to be used anywhere in codes toprint progressbar.