bash - Validate an IP before using scp -
i'm writing file transfer script , gets pretty complex. in beginning when generate ip address transfer from, want validate can indeed connect it. code in area looks this:
user_id=$1 if [[ $group == "a" ]]; address="${user_id}@morgan.company.gov" elif [[ $group == "b" ]]; address="${user_id}@mendel.company.gov" else log_msg fatal "couldn't resolve group $group. exiting" exit 1; fi // here want test $address exists, , can connect right // have below. think there better way ssh -q $address exit if [ $? != 0 ]; log_msg fatal "couldn't resolve host, have login privileges $address" fi ... // lots of other things happen scp $address:$incoming_file $new_file
what have works, doesn't seem elegant solution. i'd prefer not ssh , exit server, test connection.
you can use shell function tests wether host has ssh port open or not:
#!/bin/bash function isup(){ local ip=$1 local sshport=22 if [[ $ip =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; if [[ $(nmap -p0 $ip -p$sshport | grep ^$sshport | cut -d' ' -f2) == "open" ]]; return 0 else return 1 fi fi } if isup $1; ssh $1 uptime else echo "host $1 not available" fi
or make use of (new me) bash functionality:
#!/bin/bash function isup(){ local ip=$1 if echo > /dev/tcp/$ip/22 >/dev/null 2>&1; return 0 else return 1 fi }
Comments
Post a Comment