How to create a bash script to check the SSH conne

2020-01-27 01:05发布

I am in the process of creating a bash script that would log into the remote machines and create private and public keys.

My problem is that the remote machines are not very reliable, and they are not always up. I need a bash script that would check if the SSH connection is up. Before actually creating the keys for future use.

11条回答
趁早两清
2楼-- · 2020-01-27 01:24

You can use something like this

$(ssh -o BatchMode=yes -o ConnectTimeout=5 user@host echo ok 2>&1)

This will output "ok" if ssh connection is ok

查看更多
Melony?
3楼-- · 2020-01-27 01:27
ssh -q -o "BatchMode=yes" -i /home/sicmapp/.ssh/id_rsa <ID>@<Servername>.<domain> "echo 2>&1" && echo $host SSH_OK || echo $host SSH_NOK
查看更多
倾城 Initia
4楼-- · 2020-01-27 01:27

If you would like to check a remote folder exists, or any other file-test really:

if [ -n "$(ssh "${user}@${server}" [ -d "$folder" ] && echo 1; exit)" ]; then
    # exists
else
    # doesn't exist
fi

Do not forget the quotes in "$(ssh ...)".

查看更多
祖国的老花朵
5楼-- · 2020-01-27 01:28

Example Using BASH 4+ script:

# -- ip/host and res which is result of nmap (note must have nmap installed)
ip="192.168.0.1"
res=$(nmap ${ip} -PN -p ssh | grep open)

# -- if result contains open, we can reach ssh else assume failure) --
if [[ "${res}" =~ "open" ]] ;then
    echo "It's Open! Let's SSH to it.."
else
    echo "The host ${ip} is not accessible!"
fi
查看更多
成全新的幸福
6楼-- · 2020-01-27 01:30

https://onpyth.blogspot.com/2019/08/check-ping-connectivity-to-multiple-host.html

Above link is to create Python script for checking connectivity. You can use similar method and use:

ping -w 1 -c 1 "IP Address" 

Command to create bash script.

查看更多
SAY GOODBYE
7楼-- · 2020-01-27 01:33

To connect to a server with multiple interfaces

ssh -o ConnectTimeout=1 -q Necktwi@192.168.1.61;[ $? = 1 ] || ssh -o ConnectTimeout=1 -q Necktwi@192.168.1.51
查看更多
登录 后发表回答