Additional prompt appearing after scp completes - unix

after the scp completes in this code an additional prompt appears. I've tried several things to prevent this from happening, but it still appears. To be clear, two prompts appear after the for loop and then the program continues.
#!/usr/bin/expect
# Set timeout
set timeout 1
# Set the user and pass
set user "user"
set pass "pass"
# Get the lists of hosts, one per line
set f [open "hosts.txt"]
set hosts [split [read $f] "\n"]
close $f
# Get the commands to run, one per line
set f [open "commands.txt"]
set commands [split [read $f] "\n"]
close $f
# Clear console
set clear "clear"
# Iterate over the hosts
foreach host $hosts {
# Establish ssh conn
spawn ssh $user#$host
expect "password:"
send "$pass\r"
# Iterate over the commands
foreach cmd $commands {
expect "$ "
send "$cmd\r"
expect "password:"
send "$pass\r"
}
# Tidy up
# expect "$ "
# send "exit\r"
# expect eof
# send "close"
}

Because both your hosts and commands lists end with an empty string. Verify with puts [list $hosts $commands]
So you send an empty command, which is just "hitting enter". Then you wait for the password prompt, time-out in 1 second, and carry on with the program.
This is due to the way you're reading the files: read grabs the file contents, including the file's trailing newline. Then, when you split the string on newline, the list will include the empty string following the trailing newline.
Do this instead:
set commands [split [read -nonewline $f] "\n"]
# ........................^^^^^^^^^^
See https://tcl.tk/man/tcl8.6/TclCmd/read.htm
You could also do this
set f [open "commands.txt"]
while {[gets $f line] != -1} {
# skip empty lines and commented lines (optional)
if {[regexp {^\s*(#|$)} $line]} continue
lappend commands [string trim $line]
}
close $f

Related

Cron Expect Script

I'm trying to schedule an expect script that I have written with Cron. It is not working as expected. This is my code, my entry in the cron file, and the shell file containing the command to run the script. Any help is appreciated.
#!/usr/bin/expect
# Set timeout
set timeout 1
# Set the user and pass
set user "user"
set pass "pass"
# Get the lists of hosts, one per line
set f [open "hosts.txt"]
set hosts [split [read $f] "\n"]
close $f
# Get the commands to run, one per line
set f [open "commands.txt"]
set commands [split [read -nonewline $f] "\n"]
close $f
# Iterate over the hosts
foreach host $hosts {
# Establish ssh conn
spawn ssh $user#$host
expect "password:"
send "$pass\r"
# Iterate over the commands
foreach cmd $commands {
expect "$ "
send "$cmd\r"
expect "password:"
send "$pass\r"
expect "$ "
}
}
0,15,30,45 * * * * /home/car02fv/updatelogs.sh #fetch application logs (dbg,api,ch)
#!/bin/sh
rm goxsd1697/* goxsd1698/* goxsd1699/* goxsd1700/* | /home/car02fv/getlogs.sh
This answer comes from the discussion I had with Camilo above.
To check the error log and running the script every 15 minutes,
*/15 * * * * /home/car02fv/updatelogs.sh >/tmp/cron_out 2>&1
was run to check the output file /tmp/cron_out, using
vi /tmp/cron_out
Also, you need to give permission to the file by chmod u+x /home/car02fv/updatelogs.sh to make the script executable.
You are not providing the full path to the files you need to read. Cron scripts usually have PWD as /.
Assuming the "hosts.txt" and "commands.txt" are in /home/car02fv, you can do
0,15,30,45 * * * * cd /home/car02fv && ./updatelogs.sh
However, this is more robust: assuming you keep those text files in the same place as the script file: add to the expect script (near the top)
set dir [file dirname [info script]]
then, open the files like this:
set hostfile [file join $dir hosts.txt]
if {![file exists $hostfile]} {error "$hostfile does not exist"}
set f [open $hostfile]
# ...
set cmdfile [file join $dir commands.txt]
if {![file exists $cmdfile]} {error "$cmdfile does not exist"}
set f [open $hoscmdfiletfile]
and the cron entry stays like you have it.
BTW, ".sh" is a misleading file extension for an expect file.
#!/bin/sh
while true; do
rm goxsd1697/* goxsd1698/* goxsd1699/* goxsd1700/* | /home/car02fv/getlogs.sh
sleep 120
done

Unable to use -C of grep in Unix Shell Script

I am able to use grep in normal command line.
grep "ABC" Filename -C4
This is giving me the desired output which is 4 lines above and below the matched pattern line.
But if I use the same command in a Unix shell script, I am unable to grep the lines above and below the pattern. It is giving me output as the only lines where pattern is matched and an error in the end that cannot says cannot open grep : -C4
The results are similar if I use -A4 and -B4
I'll assume you need a portable POSIX solution without the GNU extensions (-C NUM, -A NUM, and -B NUM are all GNU, as are arguments following the pattern and/or file name).
POSIX grep can't do this, but POSIX awk can. This can be invoked as e.g. grepC -C4 "ABC" Filename (assuming it is named "grepC", is executable, and is in your $PATH):
#!/bin/sh
die() { echo "$*\nUsage: $0 [-C NUMBER] PATTERN [FILE]..." >&2; exit 2; }
CONTEXT=0 # default value
case $1 in
-C ) CONTEXT="$2"; shift 2 ;; # extract "4" from "-C 4"
-C* ) CONTEXT="${1#-C}"; shift ;; # extract "4" from "-C4"
--|-) shift ;; # no args or use std input (implicit)
-* ) [ -f "$1" ] || die "Illegal option '$1'" ;; # non-option non-file
esac
[ "$CONTEXT" -ge 0 ] 2>/dev/null || die "Invalid context '$CONTEXT'"
[ "$#" = 0 ] && die "Missing PATTERN"
PATTERN="$1"
shift
awk '
/'"$PATTERN"'/ {
match='$CONTEXT'
for(i=1; i<=CONTEXT; i++) if(NR>i) print last[i];
print
next
}
match { print; match-- }
{ for(i='$CONTEXT'; i>1; i--) last[i] = last[i-1]; last[1] = $0 }
' "$#"
This sets up die as a fatal error function, then finds the desired lines of context from your arguments (either -C NUMBER or -CNUMBER), with an error for unsupported options (unless they're files).
If the context is not a number or there is no pattern, we again fatally error out.
Otherwise, we save the pattern, shift it away, and reserve the rest of the options for handing to awk as files ("$#").
There are three stanzas in this awk call:
Match the pattern itself. This requires ending the single-quote portion of the string in order to incorporate the $PATTERN variable (which may not behave correctly if imported via awk -v). Upon that match, we store the number of lines of context into the match variable, loop through the previous lines saved in the last hash (if we've gone far enough to have had them), and print them. We then skip to the next line without evaluating the other two stanzas.
If there was a match, we need the next few lines for context. As this stanza prints them, it decrements the counter. A new match (previous stanza) will reset that count.
We need to save previous lines for recalling upon a match. This loops through the number of lines of context we care about and stores them in the last hash. The current line ($0) is stored in last[1].

Error Handling while running sqlplus from shell scripts

I need to validate whether DB connection is success/failure.
This is my code
report=`sqlplus -S /nolog << EOF
WHENEVER OSERROR EXIT 9;
WHENEVER SQLERROR EXIT SQL.SQLCODE;
connect <<username>>/<<Password>>#hostname:port
set linesize 1500
set trimspool on
set verify off
set termout off
set echo off
set feedback off
set heading on
set pagesize 0
spool extract.csv
<<My SQL Query>>
spool off;
exit;
EOF`
I have tried the below option based on the thread Managing error handling while running sqlplus from shell scripts but its picking the first cell value rather than the connection status.
if [ $report != 0 ]
then
echo "Connection Issue"
echo "Error code $sql_return_code"
exit 0;`enter code here`
fi
Please advise.
I needed something similar but executed it a bit differently.
First, I have list.txt which contains the databases that I would like to test. I am using wallet connections but this could be edited to hold username/password.
list.txt:
DB01 INSTANCE1.SCHEMA1
DB02 INSTANCE2.SCHEMA2
DB03 INSTANCE3.SCHEMA3
DB04 INSTANCE4.SCHEMA4
I have OK.sql which contains the query that I want to run on each database.
OK.sql:
select 'OK' from dual;
exit
Last, I user test.sh to read list.txt, attempt to connect and run OK.sql on each line, and record the result in (drumroll) result.txt.
test.sh:
. /etc/profile
rm result.txt
while read -r name wallet; do
echo "BEGIN-"$name
if (sqlplus -S /#$wallet #OK.sql < /dev/null | grep -e 'OK'); then
echo $name "GOOD" >> result.txt
else
echo $name "BAD" >> result.txt
fi
echo "END-"$name
done < list.txt
After the run check your result.txt.
result.txt:
DB01 BAD
DB02 GOOD
DB03 GOOD
DB04 GOOD
I hope this helps.

How to log data of a call

I want to log data of asterisk command line. But the criteria is I want log data for calls separately, i.e. I want to log data for each call in separate file.
Is there a way to do that?
In case there is no inbuild feature in asterisk to do this, here is a bash solution:
#!/bin/bash
echo "0" >/tmp/numberoflines
IFS=''
pathToLogFile = /path/to/log/file
while [ 1 ]
do
NUMBER=$(cat /tmp/numberoflines)
LINECOUNT=$(wc -l < $pathToLogFile)
DIFFERENCE=$(($LINECOUNT-$NUMBER))
if [ $DIFFERENCE != 0 ]; then
lines=($(tail -n $DIFFERENCE $pathToLogFile))
for line in $lines; do
callID = `expr "$line" : 'CALLID_REGEX (see below)'`
$(echo "$line" >> /path/to/log/directory/$callID)
done
fi
sleep 5;
echo "$LINECOUNT" >/tmp/numberoflines
done
untested
it should be used to get ab idea to solve this problem.
the regular expression: normaly: /\[(C\d{8})\]/. sadly I don't know the syntax in bash. I'm sorry. you have to convert it by yourself into bash-syntax.
The idea is: remember the last line in the logfile that was processed by the bash script. check the line count of the log file. if there are more lines then the remembered line: walk through the new lines and extract the call id at the beginning of each line (format: C******** (* are numbers). in words: a C followed by a number with 8 digits). now append the whole line at the end of a log file. the name of the file is the extracted callid.
EDIT Information about the call id (don't mistake it with the caller id): https://wiki.asterisk.org/wiki/display/AST/Unique+Call-ID+Logging

How to set font color for STDOUT and STDERR

I want to differentiate the STDOUT and STDERR messages in my terminal.
If a script or command is printing a message in terminal I want to differentiate by colors; is it possible?
(E.g. stderr font color is red, and stdout font color is blue.)
Example (using bold):
$date
Wed Jul 27 12:36:50 IST 2011
$datee
bash: datee: command not found
$alias ls
alias ls='ls --color=auto -F'
$aliass ls
bash: aliass: command not found
Create a function in a bash shell or script:
color()(set -o pipefail;"$#" 2>&1>&3|sed $'s,.*,\e[31m&\e[m,'>&2)3>&1
Use it like this:
$ color command -program -args
It will show the command's stderr in red.
Keep reading for an explanation of how it works. There are some interesting features demonstrated by this command.
color()... — Creates a bash function called color.
set -o pipefail — This is a shell option that preserves the error return code of a command whose output is piped into another command. This is done in a subshell, which is created by the parentheses, so as not to change the pipefail option in the outer shell.
"$#" — Executes the arguments to the function as a new command. "$#" is equivalent to "$1" "$2" ...
2>&1 — Redirects the stderr of the command to stdout so that it becomes sed's stdin.
>&3 — Shorthand for 1>&3, this redirects stdout to a new temporary file descriptor 3. 3 gets routed back into stdout later.
sed ... — Because of the redirects above, sed's stdin is the stderr of the executed command. Its function is to surround each line with color codes.
$'...' A bash construct that causes it to understand backslash-escaped characters
.* — Matches the entire line.
\e[31m — The ANSI escape sequence that causes the following characters to be red
& — The sed replace character that expands to the entire matched string (the entire line in this case).
\e[m — The ANSI escape sequence that resets the color.
>&2 — Shorthand for 1>&2, this redirects sed's stdout to stderr.
3>&1 — Redirects the temporary file descriptor 3 back into stdout.
Here's a hack that I thought of and it seems to work:
Given the following aliases for readability:
alias blue='echo -en "\033[36m"'
alias red='echo -en "\033[31m"'
alias formatOutput='while read line; do blue; echo $line; red; done'
Now, you need to first set the font color in your terminal to red (as the default, which will be used for stderr).
Then, run your command and pipe the stdout through formatOutput defined above (which simply prints each line as blue and then resets the font color to red):
shell$ red
shell$ ls / somenonexistingfile | formatOutput
The above command will print in both stderr and stdout and you'll see that the lines are coloured differently.
Hope this helps
UPDATE:
To make this reusable, I've put it all in a small script:
$ cat bin/run
#!/bin/bash
echo -en "\033[31m" ## red
eval $* | while read line; do
echo -en "\033[36m" ## blue
echo $line
echo -en "\033[31m" ## red
done
echo -en "\033[0m" ## reset color
Now you can use this with any command:
$ run yourCommand
I color stderr red by linking the file descriptor to a custom function that adds color to everything that goes through it. Add to following to your .bashrc:
export COLOR_RED="$(tput setaf 1)"
export COLOR_RESET="$(tput sgr0)"
exec 9>&2
exec 8> >(
perl -e '$|=1; while(sysread STDIN,$a,9999) {print
"$ENV{COLOR_RED}$a$ENV{COLOR_RESET}"}'
)
function undirect(){ exec 2>&9; }
function redirect(){ exec 2>&8; }
trap "redirect;" DEBUG
PROMPT_COMMAND='undirect;'
So what is happening? The debug trap is executed just before and immediately after executing a command. stderr is thus redirected before a command is executed to enable red output. PROMPT_COMMAND is evaluated before the prompt is shown and with this I restore stderr to its normal state. This is necessary because PS1 and PS2 (your prompt) are printed over stderr and I do not want a red prompt. voila, red output over stderr!
You should check out stderred: https://github.com/sickill/stderred
Yes it's not possible natively. You'll have to hack the tty management (in the kernel).
I somehow finished some little C wrapper before I saw the other answers :-)
Might be buggy, and values are hardcoded, don't use this except for testing.
#include "unistd.h"
#include "stdio.h"
#include <sys/select.h>
int main(int argc, char **argv)
{
char buf[1024];
int pout[2], perr[2];
pipe(pout); pipe(perr);
if (fork()!=0)
{
close(1); close(2);
dup2(pout[1],1); dup2(perr[1],2);
close(pout[1]); close(perr[1]);
execvp(argv[1], argv+1);
fprintf(stderr,"exec failed\n");
return 0;
}
close(pout[1]); close(perr[1]);
while (1)
{
fd_set fds;
FD_ZERO(&fds);
FD_SET(pout[0], &fds);
FD_SET(perr[0], &fds);
int max = pout[0] > perr[0] ? pout[0] : perr[0];
int v = select(max+1, &fds, NULL, NULL, NULL);
if (FD_ISSET(pout[0], &fds))
{
int r;
r = read(pout[0], buf, 1024);
if (!r) {close(pout[0]); continue;}
write(1, "\033[33m", 5);
write(1, buf, r);
write(1, "\033[0m", 4);
}
if (FD_ISSET(perr[0], &fds))
{
int r;
r = read(perr[0], buf, 1024);
if (!r) {close(perr[0]); continue;}
write(2, "\033[31m", 5);
write(2, buf, r);
write(2, "\033[0m", 4);
}
if (v <= 0) break;
}
return 0;
}
Edit: Compared to the shell solution, this one will preserve the order of lines/characters more often. (It's not possible to be as accurate as direct tty reading.) Hitting ^C won't show an ugly error message, and it behaves correctly on this example:
./c_color_script sh -c "while true; do (echo -n a; echo -n b 1>&2) done"
I'm surprised that nobody has actually figured out how to color stdio streams. This will color stderr red for the entire (sub)shell:
exec 3>&2
exec 2> >(sed -u 's/^\(.*\)$/'$'\e''[31m\1'$'\e''[m/' >&3)
In this case, &3 will hold the original stderr stream.
You should not be passing any commands to exec, only the redirects. This special case causes exec to replace the current (sub)shell's stdio streams with those that it receives.
There are a few caveats:
Since sed will be running persistently in a parallel subshell, any direct output immediately following a write to the colored stdio will probably beat sed to the tty.
This method uses a FIFO file descriptor; FIFO nodes only deal in lines. If you don't write a linefeed to the stream, your output will be buffered until a newline is encountered. This is not buffering on sed's part: it's how these file types function.
The most troublesome of the caveats is the first, but a race condition can be more or less avoided by applying similar processing to all outputs, even if you use the default color.
You can perform similar processing for single commands by piping to the same sed command with the normal pipe operator (|). Piped chains are executed synchronously, so no race condition will occur, though the last command in a pipe chain receives its own subshell by default.
Expanding on the answer #gospes gave, I added the functionality to print out partial lines without waiting for a newline, and some comments. Allows for better output from wget or typing in a interactive shell.
exec 9>&2
exec 8> >(
while [ "$r" != "1" ]; do
# read input, no field separators or backslash escaping, 1/20th second timeout
IFS='' read -rt 0.05 line
r=$?
# if we have input, print the color change control char and what input we have
if ! [ "${#line}" = "0" ]; then
echo -ne "\e[1;33m${line}"
fi
# end of line detected, print default color control char and newline
if [ "$r" = "0" ] ; then
echo -e "\e[0m"
fi
# slow infinite loops on unexpected returns - shouldn't happen
if ! [ "$r" = "0" ] && ! [ "$r" = "142" ]; then
sleep 0.05
fi
done
)
function undirect(){ exec 2>&9; }
function redirect(){ exec 2>&8; }
trap "redirect;" DEBUG
PROMPT_COMMAND='undirect;'
I used bold yellow (1;33) but you can replace it with whatever, red for example (31) or bold red (1;33), and I arbitrarily chose 0.05 seconds for re-checking for end-of-lines and pausing on unexpected return codes (never found any); it could probably be lowered, or possibly removed from the read command.
You can make use of grep for this. Note that this assumes that grep is configured to have coloured output (this is the default on many systems).
$ aliass ls 2> >(GREP_COLORS='ms=01;31' grep .) 1> >(GREP_COLORS='ms=01;32' grep .)
aliass: command not found
This is a little long winded, if you are simply wanting to distinguish stderr fromstdout you can simply do this:
$ (echo "this is stdout"; echo "this is stderr" >&2) | grep .
this is stderr
this is stdout
This will result in stdout being highlighted with the default grep colour and stderr being white.
This might be the opposite of what you want if your default grep colour is red. If so you can explicitly set the grep colour to green:
$ GREP_COLORS='ms=01;32'
$ (echo "this is stdout"; echo "this is stderr" >&2) | grep .
If you explicitly want to get red output for stderr:
$ GREP_COLORS='ms=01;31'
$ (echo "this is stdout"; echo "this is stderr" >&2) 2> >(grep .)
Note that this solution will not preserve the output order.

Resources