Norstorin
Norstorin

Reputation: 71

How can I use grep to find the output of command

I am trying to cycle through some ports for connecting via ssh. New to shell/bash not quite sure how to accomplish this.

startingPort=xxxx
endingPort=yyyy

ssh(){
ssh admin@localhost -p $startingPort
}

the output of an invalid port is ssh: connect to host localhost port 8801: Connection refused I need to capture this and then try the next port in the range

I am trying to iterate through the port numbers until i see Password authentication Password:

Upvotes: 2

Views: 194

Answers (3)

Norstorin
Norstorin

Reputation: 71

Thank you muzido and Theo Pnv; the two answers combined helped me get this task accomplished..

log_file=/directory/log_file.txt
startingPort=8801 
endingPort=8899
port=''

sshToStuff(){
for (( port=$startingPort; port<=$endingPort; port++ ))
do
if [ "$?" -ne 0 ] ; then
    echo "`date -u`" " ssh: connect to host localhost port $port: Connection refused" >> $log_file2;
fi


ssh admin@localhost -p $port
done
}
sshToKaraf

Upvotes: 1

Theo Pnv
Theo Pnv

Reputation: 432

To get the output of the ssh command, you can check it with "$?". As an example, if you want to log errors :

//inside the loop (of muzido answer)
ssh admin@localhost -p $port
if [ "$?" -ne 0 ] ; then
    //write into logfile
fi

Upvotes: 1

Mustafa DOGRU
Mustafa DOGRU

Reputation: 4112

try something like this;

#!/bin/bash
startingPort=10
endingPort=40

for (( port=$startingPort; port<=$endingPort; port++ ))
do
ssh admin@localhost -p $port
done

Upvotes: 0

Related Questions