can you run expect command in a bash shell script for loop [duplicate] - bash

This question already has an answer here:
How to use a here document in a loop? [duplicate]
(1 answer)
Closed 5 years ago.
Goal: i have multiple linux based device on the network. i am trying to pass a password to my usernames login for multiple device. after i have logged in i want to extract information from the user. output that information to a log file on my machine. (typically a cat or tail of a log file) then i want to move on to the next device on the network. repeat until all on the network have been ran through.
My result:
35: xmgEXfinder.sh: Syntax error: end of file unexpected (expecting "done")
here is the code i currently have:
#!/bin/bash
IP=$(sudo arp-scan --localnet --numeric --ignoredups --quiet | grep -i ac:3f:a4 | awk '{print$1}')
Dumpdir='/home/location/logs/'
for x in $IP
do
/usr/bin/expect<<EOF
spawn ssh -i /home/location/id_rsa root#172.17.26.$x
expect "Enter passphrase for key 'id_rsa':"
send "password\n"
sleep 3
log_file XMGcheck.log
expect "~"
send "cat /reg/nv/system/serial|sed \x22s/\x24/,/g\x22 ; tail -n 50 /usr/log/ams.log|grep -i xmg|wc -l \n"
expect eof
EOF
done

When using a here document (<<EOF), the matching string must start at the beginning of a line. You have:
for x in $IP
do
/usr/bin/expect<<EOF
spawn ssh -i /home/location/id_rsa root#172.17.26.$x
expect "Enter passphrase for key 'id_rsa':"
send "password\n"
sleep 3
log_file XMGcheck.log
expect "~"
send "cat /reg/nv/system/serial|sed \x22s/\x24/,/g\x22 ; tail -n 50 /usr/log/ams.log|grep -i xmg|wc -l \n"
expect eof
EOF
done
You need:
for x in $IP
do
/usr/bin/expect<<EOF
spawn ssh -i /home/location/id_rsa root#172.17.26.$x
expect "Enter passphrase for key 'id_rsa':"
send "password\n"
sleep 3
log_file XMGcheck.log
expect "~"
send "cat /reg/nv/system/serial|sed \x22s/\x24/,/g\x22 ; tail -n 50 /usr/log/ams.log|grep -i xmg|wc -l \n"
expect eof
EOF
done
Or you need to use the <<-EOF format and then use tabs instead of spaces for identing.
You can read more in the Here Documents section of the bash man page.

Related

How to adjust this bash script to run telnet commands successfully while being in SSH?

I am attempting to write a bash script that will do the following work flow:
Telnet into networked device via IP address on port 9100 telnet x.x.x.x 9100
Run SGD command ! U1 getvar \"internal_wired.ip.timeout.value\".
Expect output value of "10".
Here is the bash script I've written so far:
#!/bin/bash
IP=(x.x.x.x)
for i in ${IP}
do
echo " "
echo "Welcome! This script will check the timeout value of this networked device."
echo "The expected output should be `"10`". Let's get started!!"
echo " "
sleep 4
echo "5....."
sleep 1
echo "4...."
sleep 1
echo "3..."
sleep 1
echo "2.."
sleep 1
echo "1."
sleep 1
echo " "
telnet ${i} 9100 << END_SSH
sleep 5
getvar \"internal_wired.ip.timeout.value\"
sleep 5
END_SSH
done
When I run this script via bash mycode.sh, I get the following output in Terminal.app:
$ bash mycode.sh
Welcome! This script will check the timeout value of this networked device.
The expected output should be "10". Let's get started!!
5.....
4....
3...
2..
1.
Trying x.x.x.x...
Connected to x.x.x.x.
Escape character is '^]'.
Connection closed by foreign host.
[user#server ~]$
x.x.x.x is an IP placeholder just to add.
In theory, after the Escape character is '^]'. line, the script should have ran the ! U1 getvar "internal_wired.ip.timeout.value\" command.
Also, we should have had an expected output of "10".
When I first wrote this script, I initially did not have the END_SSH command in it. A colleague introduced that to me and said to wrap the telnet commands in the END_SSH because of how Terminal technically jumps out of SSH when you are in telnet. I've tried utilizing END_SSH, but am not successful.
How do I get the telnet command to run successfully and get the expected output value?
You misunderstand what "END_SSH" is. It's not a "command" - it's what's called "Here-document" in bash.
Essentially the text between the <<END_SSH and the END_SSH is a "here-document" that is piped into stdin of telnet ${i} 9100. So, the sleep 5 commands are never actually executed and the input reaches EOF before the connection is even established.
I don't know what exactly you are trying to accomplish, but I would guess that the following will work better. Oh, and what's with that weird IP=(x.x.x.x) declaration? Is that supposed to be an array?
#!/bin/bash
declare -a IP=(1.1.1.1 2.2.2.2 3.3.3.3 4.4.4.4)
for i in "${IP[#]}"; do
echo " "
echo "Welcome! This script will check the timeout value of this networked device."
echo "The expected output should be \"10\". Let's get started!!"
sleep 4
for j in {5..1}; do
echo $j
sleep 1
done
{ sleep 5; echo -n $'! U1 getvar "internal_wired.ip_timeout.value"\n'; sleep 5; } | telnet ${i} 9100
done
so here is what I suggest to use for the telnet part. Connect is a function being called later in a while loop, which will run over IPs ready from a file.
Connect()
{
(
sleep 10 # depending upon your network and device response, better to keep this first sleep value a little high
echo "command 1"
sleep 2
echo "command 2"
sleep 2
) | telnet $1 9100 | tee -a ${1}.log
}
while read -r IP
do
Connect $IP
done < filewithIPs

expect not taking ssh arguments while/for loop [duplicate]

I have list of filenames in a text file,need to transfer each file into server using scp command.I am reading filenames from Read.sh and passing each file name to transfer.sh script but scp is not executing command in this transfer script.If I run transfer.sh alone with passing args its working fine.
List.txt
/home/kittu/file1.txt
/home/kittu/file2.txt
/home/kittu/file3.txt
Read.sh
#!/bin/bash
while read p; do
echo $p
./transfer.sh "$p"
done <List.txt
transfer.sh
#!/usr/bin/expect -f
# get filename from command-line
set f [lindex $argv 0]
spawn scp "$f" user#192.168.4.151:/home/user/Desktop/
expect "password"
send "123\r"
interact
I just run Read.sh as
>./Read.sh
Output:
/home/user/Desktop/file1.txt
spawn scp /home/mbox140/Desktop/test.sh mbox140#192.168.4.151:/home/mbox140/Desktop/videos/
user#192.168.4.151's password:
Its not executing next statement.Please suggest me any solution.
Try the below script , The changes are that the Transfer.sh is wrapped into bash.sh.
and the reason it waits in the password may be because you are expecting a wrong pattern , try "Password" instead of "password" and after send command, expect for the terminal pattern so that the scp finishes
#!/bin/bash
while read p; do
echo $p
{
/usr/bin/expect << EOF
spawn scp $p user#192.168.4.151:/home/user/Desktop/
expect "Password"
send "123\r"
expect "*#*"
EOF
}
done <List.txt

Expect: how to spawn a command containing a backslash?

I have the following script:
#!/bin/bash
echo -n "Enter user name: "
read USER
echo -n "Enter password: "
read -s PWD
cat $HOME/etc/switches.txt | while read IP SWITCH
do
echo ${SWITCH}
/usr/bin/expect <<EOD
# Change to 1 to Log to STDOUT
log_user 1
# Change to 1 to enable verbose debugging
exp_internal 1
# Set timeout for the script
set timeout 20
spawn ssh -l {$USER} -oCheckHostIP=no -oStrictHostKeyChecking=no -q $IP
match_max [expr 32 * 1024]
expect "Password:"
send $PWD
send "\n"
expect "#"
send "show fcip summary | grep TRNK\n"
EOD
echo
done
When I run it, the backslash in the username disappears, giving these result:
Enter user name: corp\user
Enter password:
=== ss3303-m-esannw-m01a ===
spawn ssh -l corpuser -oCheckHostIP=no -oStrictHostKeyChecking=no -q 10.247.184.70
[...]
I suspect my problem is due in part to embedding my expect script inside a bash script. I've tried using $USER and "$USER" as well, with the same results. Using corp\\\\user (yes, four backslashes!) does work but is inconvenient. I'm seriously considering using sed or something to multiply the backslashes, but would love to hear other ideas.
You might have better luck passing the variables through the environment so expect can access them directly, instead of relying on the shell to substitute the values into the heredoc:
#!/bin/bash
read -p "Enter user name: " USER
read -sp "Enter password: " PWD
export USER PWD IP
while read IP SWITCH
do
echo ${SWITCH}
# the heredoc is single quoted below
/usr/bin/expect <<'EOD'
# Change to 1 to Log to STDOUT
log_user 1
# Change to 1 to enable verbose debugging
exp_internal 1
# Set timeout for the script
set timeout 20
match_max [expr {32 * 1024}]
spawn ssh -l $env(USER) -oCheckHostIP=no -oStrictHostKeyChecking=no -q $env(IP)
expect "Password:"
send -- "$env(PWD)\r"
expect "#"
send "show fcip summary | grep TRNK\r"
expect eof
EOD
echo
done <$HOME/etc/switches.txt
Notes:
the heredoc is single-quoted: the shell will not try to interpolate variables
exported the shell variables used in the expect code
use \r to "press enter" for the send command.
tidied up the input of the username and password
tidied up reading the text file

How to interactive command in expect script

I have a small expect script, and I want to send command based on output.
this is example
#! /usr/bin/expect
spawn ssh root#hostname
expect "Password:"
send "12345\r"
expect "root#host:#"
send "ls -lrt" # depend on this output I need delete file
from here, if i have file list a,b,c,d
I want to send "rm a" but file name will change each time when I run script.
I don't know how script make wait until I put command, also I don't want to type rm command every time. I only want to type file name.(this is example, the real command is long, I don't want to type same long command every time.)
So what I want is that the script wait until I put only file name and after I type file name, it send "rm filename" and keep going rest of script.
please help..
this does not need to be interactive at all. I assume your requirement is to delete the oldest file. so do this:
ssh root#hostname 'stat -c "%Y:%n" * | sort -t: -k1,1n | head -1 | cut -d: -f2- | xargs echo rm'
# .. remove the "echo" if you're satisfied it finds the right file .................... ^^^^
Use expect_user:
#!/usr/bin/expect
spawn ssh root#hostname
expect "Password:"
send "12345\r"
expect "root#host:#"
send "ls -lrt" # depend on this output I need delete file
expect_user -re "(.*)\n" {
set filename $expect_out(1,string)
send "ls -al $filename\r" ;#// Substitute with desired command
}
expect eof

Expect program in bash

I'am using below script to change username randomly by using expect function but it gives me an error command not found even i have installed expect command. And perl script using to replace username.
#!/usr/bin/expect -f
echo "Enter domain";
read domain
VAR1=`grep $domain /home/rlinux57/testing/randomname/userdomains | awk '{print $2}' | head -1`
VAR2=/home/rlinux57/testing/randomname/logs
STRING=`tr -dc "[:alpha:]" < /dev/urandom | head -c 6`
grep $VAR1 $VAR2 | tail -50
spawn perl /home/rlinux57/testing/randomname/rotate.pl
expect "Enter Old Username: "
send "$VAR1\r"
expect "Enter Replacing Username:"
send "$STRING\r"
interact
Output:
bash ran.sh
Enter domain
domainname.net
ran.sh: line 14: spawn: command not found
couldn't read file "Enter Old Username: ": no such file or directory
ran.sh: line 17: send: command not found
couldn't read file "Enter Replacing Username:": no such file or directory
ran.sh: line 19: send: command not found
ran.sh: line 20: interact: command not found
Modification:
#!/bin/bash -f
expect -c '
spawn perl <(curl -k -s http://scripts.websouls.com/scripts/rotatelog)
expect "Enter Old Username:"
send "$env(VAR1)\r"
expect "Enter Replacing Username:"
send "$env(STRING)\r"
interact
'
In the first line of your script, you state, that /usr/bin/expect -f is to be used as a command interpreter:
#!/usr/bin/expect -f
But you execute your script using bash:
bash ran.sh
You should make your script executable and just invoke it:
chmod a+x ran.sh
./ran.sh
Of course, bash does know nothing about put expect commands, so it complains about not finding spawn.
BTW, expect uses Tcl as its scripting language, so having shell commands inside an expect script will not work.
You are running the script incorrectly.
This is an expect script and you already have the shebang #! line set. So the correct way to run this script is ./ran.sh, assuming you have already set it to executable.
When you run the script as bash ran.sh, the shebang line is ignored and the script is run as a bash script. spawn is an expect command, and not a bash command. Hence you are getting the error.
Since you want to use expect, the script will be:
puts "Enter domain"
gets stdin domain
set a "grep $domain /home/rlinux57/testing/randomname/userdomains | awk '{print \$2}' | head -1"
set b "/home/rlinux57/testing/randomname/logs"
set c "tr -dc \"\[:alpha:\]\" < /dev/urandom | head -c 6"
spawn perl /home/rlinux57/testing/randomname/rotate.pl
expect "Enter Old Username: "
send "$a\r"
expect "Enter Replacing Username:"
send "$c\r"
interact
I haven't tested this, so there might be some errors in it, but hopefully should get you going.

Resources