john
john

Reputation: 1075

Using Bash to determine if URL is HTTP or HTTPS

Is there a way In bash to determine if a URL uses SSL? Before I send anything else to the URL I want to find out if it only accepts HTTP or HTTPS connections.

Upvotes: 2

Views: 5100

Answers (3)

MaXi32
MaXi32

Reputation: 668

As pointed by the comment from @anubhava, to check if a URL is valid http or https, we need to consider if the SSL port 443 is open. But sometimes we don't use this port, there could be port 899, 811 etc. This is my best solution so far:

User openssl for this:

#!/bin/bash
#usage: ./httpscheck <URL_OR_DOMAIN>:<optional_port>
#eg: ./httpcheck microsoft.com:3333
#eg2: ./httpcheck google.com (without port, default is 443)
#eg3: ./httpcheck https://www.apple.com (default port is 443)
#eg4: ./httpcheck sub1.sub2.sub3.domain.com:9991

# Get the URL or Subdomain
url="$1"

# Get the port after symbol :, if does not exist use the default port 443
port=$(echo "${url}" | awk -F':' '{ print $3 }')

if [ -z "${port}" ]; then
   port="443"
fi


# Get the final hostname because this URL might be redirected
final_hostname=$(curl "${url}" -Ls -o /dev/null -w %{url_effective} | awk -F[/:] '{ print $4 }')

# Use openssl to get the status of the host

status=$(echo | openssl s_client -connect "${final_hostname}:${port}" </dev/null 2>/dev/null | grep 'Verify return code: 0 (ok)')

if [ -n "${status}" ]; then
   echo "Site ${final_hostname} with port ${port} is valid https"
else
   echo "Site ${final_hostname} with port ${port} is not valid https"
fi

Another shorter version:

#!/bin/bash

# Validate input
if [[ ! "$1" =~ ^[a-zA-Z0-9.-]+(:[0-9]+)?$ ]]; then
  echo "Usage: $0 <URL_OR_DOMAIN>:<optional_port>"
  echo "Example: $0 example.com:3333"
  exit 1
fi

# Get the URL or Subdomain and port
url="$1"
port="${url##*:}"
port="${port:-443}"
host="${url%:*}"

# Check if site is valid https
if openssl s_client -connect "${host}:${port}" </dev/null 2>/dev/null | grep -q 'Verify return code: 0 (ok)'; then
  echo "Site ${host} with port ${port} is valid https"
  exit 0
else
  echo "Site ${host} with port ${port} is not valid https"
  exit 1
fi

Upvotes: 3

gile
gile

Reputation: 5996

  • http

    if [[ $(wget -S --spider  http://yoursite  2>&1 | grep 'HTTP/1.1 200 OK') ]]; \
    then  echo "true";  fi
    
  • https

    if [[ $(wget -S --spider https://yoursite  2>&1 | grep 'HTTP/1.1 200 OK') ]]; \
    then  echo "true";  fi
    

Upvotes: 4

Saptarshi
Saptarshi

Reputation: 76

You can use the below script if you have access to wget.

#/bin/bash    
URL=google.com
if wget --spider https://$URL 2>/dev/null; then
  echo "https is present"
else
  echo "https not present"
fi

Please note that you need to have http_proxy / https_proxy set.

I tested the above script in cygwin64 [dont have access to nix system as of now]

You should be also able to modify the same script using curl.

Upvotes: 4

Related Questions