Bash – Continue for loop by keyboard

bashforkeyboardssh

I have user account on a linux machine which I do not know its exact IP address. But I know a range which it is ran on one of them.
I want to check which server is my desired server. There are some Microsoft servers, some Linux servers and some servers that are down as well.

I have a shell script to check each server:

#!/bin/sh
for i in $(seq 1 127)
do
    echo "192.168.1.$i:"
    ssh 192.168.1.$i -l user_name
done

This code goes to each IP. If it ran ssh, it prompts for password, if ssh did not run, it tries the next ip and if server is down, it waits for a long time. Also if the server has ssh and prompts for a password, I can not escape from it by keyboard from such a server.

How can I escape from these two types by keyboard and go to the next IP without terminating the program?

For example CTRL + C terminates the program.

Best Answer

Ctrl-C sends the SIGINT signal to all the processes of the foreground job of your interactive shell. So that sends it to the sh running the script and ssh.

You can make it not kill the shell by adding a:

trap : INT

to the beginning of your script.

You may also want to use the ConnectTimeout option of ssh:

ssh -o ConnectTimeout=2 ...

Note that you're giving away your password to all those machines you're trying to connect to. Not a good idea if you don't trust their administrators.

Related Question