Programing

Bash로 인터넷 연결을 테스트하는 방법은 무엇입니까?

lottogame 2020. 8. 22. 11:30
반응형

Bash로 인터넷 연결을 테스트하는 방법은 무엇입니까?


일부 웹 사이트를 핑하지 않고 어떻게 인터넷 연결을 테스트 할 수 있습니까? 연결되어 있지만 사이트가 다운되면 어떻게됩니까? 세상과의 연결에 대한 점검이 있습니까?


핑없이

#!/bin/bash

wget -q --spider http://google.com

if [ $? -eq 0 ]; then
    echo "Online"
else
    echo "Offline"
fi

-q : 무음 모드

-거미 : 이해하지 말고 페이지 가용성을 확인하십시오.

$? : 쉘 리턴 코드

0 : 쉘 "All OK"코드

wget없이

#!/bin/bash

echo -e "GET http://google.com HTTP/1.0\n\n" | nc google.com 80 > /dev/null 2>&1

if [ $? -eq 0 ]; then
    echo "Online"
else
    echo "Offline"
fi

기본 게이트웨이를 ping합니다.

#!/bin/bash
ping -q -w 1 -c 1 `ip r | grep default | cut -d ' ' -f 3` > /dev/null && echo ok || echo error

사용자 somedrew 에게 감사드립니다 : https://bbs.archlinux.org/viewtopic.php?id=55485 on 2008-09-20 02:09:48

/ sys / class / net을 찾는 것이 한 가지 방법이어야합니다.

다음은 루프백 이외의 네트워크 연결을 테스트하는 스크립트입니다. 내 웹 사이트에 액세스 할 수 있는지 주기적으로 테스트하기 위해 다른 스크립트에서 아래를 사용합니다. 액세스 할 수없는 경우 팝업 창에서 문제를 알려줍니다.

아래 스크립트는 노트북이 네트워크에 연결되어 있지 않을 때마다 5 분마다 팝업 메시지를받지 못하도록합니다.

#!/usr/bin/bash

# Test for network conection
for interface in $(ls /sys/class/net/ | grep -v lo);
do
  if [[ $(cat /sys/class/net/$interface/carrier) = 1 ]]; then OnLine=1; fi
done
if ! [ $OnLine ]; then echo "Not Online" > /dev/stderr; exit; fi

bash를 처음 접하는 사람들을위한 참고 사항 : 마지막 'if'문은 온라인이 아닌 경우 [!] 테스트하고이 경우 종료됩니다. 자세한 내용은 man bash를 참조하고 "표현식 조합 가능"을 검색하십시오.

추신 : 핑은 어떤 종류 의 네트워크대한 연결이 있는지 테스트하지 않고 특정 호스트에 대한 연결 테스트하는 것을 목표로하기 때문에 여기서 사용하기에 가장 좋은 것이 아니라고 생각합니다 .

PPS 위는 Ubuntu 12.04에서 작동합니다. / sys는 다른 배포판에 없을 수 있습니다. 아래를 참조하십시오.

최신 Linux 배포판에는 가상 파일 시스템으로 / sys 디렉토리가 포함되어 있습니다 (sysfs, procfs 인 / proc와 비교).이 디렉토리는 시스템에 연결된 장치를 저장하고 수정할 수있는 반면 많은 기존 UNIX 및 Unix 유사 운영 체제는 / sys는 커널 소스 트리에 대한 심볼릭 링크입니다. [인용 필요]

Wikipedia https://en.wikipedia.org/wiki/Filesystem_Hierarchy_Standard에서


이것은 MacOSX와 Linux 모두에서 작동합니다.

#!/bin/bash

ping -q -w1 -c1 google.com &>/dev/null && echo online || echo offline

텔넷을 사용하여 포트 80에 연결 한 다음 텍스트를 전송하기 전에 스크립트를 작성했습니다.

HTTP/1.0 GET /index.html

두 개의 CR / LF 시퀀스가 ​​뒤 따릅니다.

어떤 형식의 HTTP 응답을 받으면 일반적으로 사이트가 작동하고 있다고 가정 할 수 있습니다.


최고의 대답은 기본 게이트웨이에 완벽하게 안정적인 연결을 가질 수 있다는 사실을 놓치지 만 이것이 인터넷에서 실제로 무언가에 도달 할 수 있다는 것을 자동으로 의미하지는 않습니다. OP는 어떻게 세상과의 연결을 테스트 할 수 있는지 묻습니다. 따라서 게이트웨이 IP를 LAN 외부에있는 알려진 IP (xyzw)로 변경하여 최상위 답변을 변경하는 것이 좋습니다.

따라서 대답은 다음과 같습니다.

ping -q -w 1 -c 1 x.y.z.w > /dev/null && echo ok || echo error

또한 명령 대체 [1]에 대해 선호하지 않는 백틱 제거 .

일부 코드를 실행하기 전에 세계에 연결되어 있는지 확인하려면 다음을 사용할 수도 있습니다.

if ping -q -w 1 -c 1 x.y.z.w > /dev/null; then
    # more code
fi

다음 명령을 실행하여 웹 사이트가 작동 중인지 확인하고 웹 서버가 표시하는 상태 메시지를 확인합니다.

$ curl -Is http://www.google.com | head -1 HTTP/1.1 200 OK

상태 코드 '200 OK'는 요청이 성공했으며 웹 사이트에 연결할 수 있음을 의미합니다.


로컬 네임 서버가 다운 된 경우

핑 4.2.2.1

is an easy-to-remember always-up IP (it's actually a nameserver, even).


make sure your network allow TCP traffic in and out, then you could get back your public facing IP with the following command

curl ifconfig.co

shortest way: fping 4.2.2.1 => "4.2.2.1 is alive"

i prefer this as it's faster and less verbose output than ping, downside is you will have to install it.

you can use any public dns rather than a specific website.

fping -q google.com && echo "do something because you're connected!"

-q returns an exit code, so i'm just showing an example of running something you're online.

to install on mac: brew install fping; on ubuntu: sudo apt-get install fping


The top voted answer does not work for MacOS so for those on a mac, I've successfully tested this:

GATEWAY=`route -n get default | grep gateway`
if [ -z "$GATEWAY" ]
  then
    echo error
else
  ping -q -t 1 -c 1 `echo $GATEWAY | cut -d ':' -f 2` > /dev/null && echo ok || echo error
fi

tested on MacOS High Sierra 10.12.6


In Bash, using it's network wrapper through /dev/{udp,tcp}/host/port:

if echo -n >/dev/tcp/8.8.8.8/53; then
  echo 'Internet available.'
else
  echo 'Offline.'
fi

Ping was designed to do exactly what you're looking to do. However, if the site blocks ICMP echo, then you can always do the telnet to port 80 of some site, wget, or curl.


Checking Google's index page is another way to do it:

#!/bin/bash

WGET="/usr/bin/wget"

$WGET -q --tries=20 --timeout=10 http://www.google.com -O /tmp/google.idx &> /dev/null
if [ ! -s /tmp/google.idx ]
then
    echo "Not Connected..!"
else
    echo "Connected..!"
fi

Similarly to @Jesse's answer, this option might be much faster than any solution using ping and perhaps slightly more efficient than @Jesse's answer.

find /sys/class/net/ -maxdepth 1 -mindepth 1 ! -name "*lo*" -exec sh -c 'cat "$0"/carrier 2>&1' {} \; | grep -q '1'

Explenation:

This command uses find with -exec to run command on all files not named *lo* in /sys/class/net/. These should be links to directories containing information about the available network interfaces on your machine.

The command being ran is an sh command that checks the contents of the file carrier in those directories. The value of $interface/carrier has 3 meanings - Quoting:

It seems there are three states:

  • ./carrier not readable (for instance when the interface is disabled in Network Manager).
  • ./carrier contain "1" (when the interface is activated and it is connected to a WiFi network)
  • ./carrier contain "0" (when the interface is activated and it is not connected to a WiFi network)

The first option is not taken care of in @Jesse's answer. The sh command striped out is:

# Note: $0 == $interface
cat "$0"/carrier 2>&1

cat is being used to check the contents of carrier and redirect all output to standard output even when it fails because the file is not readable. If grep -q finds "1" among those files it means there is at least 1 interface connected. The exit code of grep -q will be the final exit code.

Usage

For example, using this command's exit status, you can use it start a gnubiff in your ~/.xprofile only if you have an internet connection.

online() {
    find /sys/class/net/ -maxdepth 1 -mindepth 1 ! -name "*lo*" -exec sh -c 'cat "$0"/carrier 2>&1 > /dev/null | grep -q "1" && exit 0' {} \;
}
online && gnubiff --systemtray --noconfigure &

Reference


This bash script continuously check for Internet and make a beep sound when the Internet is available.

#!/bin/bash
play -n synth 0.3 sine 800 vol 0.75
while :
do
pingtime=$(ping -w 1 8.8.8.8 | grep ttl)
if [ "$pingtime" = "" ] 
then 
   pingtimetwo=$(ping -w 1 www.google.com | grep ttl) 
   if [ "$pingtimetwo" = "" ] 
   then 
       clear ; echo 'Offline'
   else
       clear ; echo 'Online' ; play -n synth 0.3 sine 800 vol 0.75
   fi 
else
    clear ; echo 'Online' ; play -n synth 0.3 sine 800 vol 0.75
fi
sleep 1
done

Pong doesn't mean web service on the server is running; it merely means that server is replying to ICMP echo. I would recommend using curl and check its return value.


If your goal is to actually check for Internet access, many of the existing answers to this question are flawed. A few things you should be aware of:

  1. It's possible for your computer to be connected to a network without that network having internet access
  2. It's possible for a server to be down without the entire internet being inaccessible
  3. It's possible for a captive portal to return an HTTP response for an arbitrary URL even if you don't have internet access

With that in mind, I believe the best strategy is to contact several sites over an HTTPS connection and return true if any of those sites responds.

For example:

connected_to_internet() {
  test_urls="\
  https://www.google.com/ \
  https://www.microsoft.com/ \
  https://www.cloudflare.com/ \
  "

  processes="0"
  pids=""

  for test_url in $test_urls; do
    curl --silent --head "$test_url" > /dev/null &
    pids="$pids $!"
    processes=$(($processes + 1))
  done

  while [ $processes -gt 0 ]; do
    for pid in $pids; do
      if ! ps | grep "^[[:blank:]]*$pid[[:blank:]]" > /dev/null; then
        # Process no longer running
        processes=$(($processes - 1))
        pids=$(echo "$pids" | sed --regexp-extended "s/(^| )$pid($| )/ /g")

        if wait $pid; then
          # Success! We have a connection to at least one public site, so the
          # internet is up. Ignore other exit statuses.
          kill -TERM $pids > /dev/null 2>&1 || true
          wait $pids
          return 0
        fi
      fi
    done
    # wait -n $pids # Better than sleep, but not supported on all systems
    sleep 0.1
  done

  return 1
}

Usage:

if connected_to_internet; then
  echo "Connected to internet"
else
  echo "No internet connection"
fi

Some notes about this approach:

  1. It is robust against all the false positives and negatives I outlined above
  2. The requests all happen in parallel to maximize speed
  3. It will return false if you technically have internet access but DNS is non-functional or your network settings are otherwise messed up, which I think is a reasonable thing to do in most cases

참고URL : https://stackoverflow.com/questions/929368/how-to-test-an-internet-connection-with-bash

반응형