使用Bash确定URL是HTTP还是HTTPS

时间:2016-08-26 14:32:04

标签: bash shell url ssl scripting

有没有办法在bash中确定URL是否使用SSL?在我向URL发送任何其他内容之前,我想知道它是否只接受HTTP或HTTPS连接。

3 个答案:

答案 0 :(得分:3)

  • HTTP

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

    [DllImport("ts3client_win32.dll", CallingConvention =   CallingConvention.Cdecl, EntryPoint = "ts3client_startConnection", CharSet = CharSet.Ansi)]
    public static extern uint ts3client_startConnection(uint64 arg0, string identity, string ip, uint port, string nick, string[] defaultchannelarray, string defaultchannelpassword, string serverpassword);
    ...
    string[] defaultarray = new string[] { "name", ""};
    /* Connect to server on localhost:9987 with nickname "client", no default channel, no default channel password and server password "secret" */
    error = ts3client.ts3client_startConnection(scHandlerID, identity, "localhost", 9987, "client", defaultarray, "password", "secret");
    if (error != public_errors.ERROR_ok) {
        Console.WriteLine("Error connecting to server: 0x{0:X4}", error);
        Console.ReadLine();
        return;
    }
    

答案 1 :(得分:3)

如果您有权访问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

请注意,您需要设置http_proxy / https_proxy。

我在cygwin64中测试了上面的脚本[截至目前无法访问nix系统]

您还应该能够使用curl修改相同的脚本。

答案 2 :(得分:0)

正如@anubhava 的评论所指出的,要检查 URL 是否是有效的 http 或 https,我们需要考虑 SSL 端口 443 是否打开。但有时我们不使用这个端口,可能有端口 899、811 等。这是我目前最好的解决方案:

用户 openssl

#!/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