Linux 使用pppd和ppp程式進行3G/4G撥號

kunkliu發表於2020-04-05

轉載地址:https://www.cnblogs.com/cryhuang/p/5649372.html

試驗環境:Linux marsboard 3.4.90 #9 SMP PREEMPT Thu Mar 3 18:28:43 CST 2016 armv7l armv7l armv7l GNU/Linux (注:A20核心板)

      通訊模組,載入成ttyUSB*裝置;

目標:使用通訊模組進行3G4G撥號連線網際網路

方法:使用pppd和ppp程式,進行撥號連線

前提:安裝了ppp、pppd兩個程式

摘要:涉及的檔案ppp的chat-script撥號指令碼(針對不通通訊裝置情況需要有所調整,此處不考慮這些情況,大部分都可以使用)、

步驟:

1、建立ppp程式的撥號指令碼,內容如下:(有兩個,一個是針對移動、聯通和電信4G的,一個是隻針對電信3G的)

# 針對移動、聯通和電信4G的,檔名chat-script

#!/bin/sh

exec chat -v \
TIMEOUT 5 \
ABORT "BUSY" \
ABORT "ERROR" \
ABORT "NO CARRIER" \
'' \rAT \
OK 'AT+CGDCONT=1,"IP","CMNET"' \
OK 'ATDT*99#' \
CONNECT '' \

-----------------不同指令碼分割,請存在不通檔案中-----------------------------------------

# 針對電信3G的,檔名chat-script-ct3g

#!/bin/sh
exec chat -v \
TIMEOUT 5 \
ABORT "BUSY" \
ABORT "ERROR" \
ABORT "NO CARRIER" \
'' \rAT \
OK 'AT+CGDCONT=1,"IP","CMNET"' \
OK 'ATDT#777' \
CONNECT '' \

 

2、建立兩個撥號指令碼,ppp-on用於撥號連線 ppp-off使用者斷開連線

# 檔案 ppp-on

#! /bin/sh

# $1 串列埠號 $2波特率 $3chat指令碼 
pppd modem -d -detach lock $1 $2 kdebug 4 file /etc/ppp/options crtscts noipdefault netmask 255.255.255.0 defaultroute connect $3

------------------------------------------------------

# 檔案 ppp-off

#!/bin/sh
######################################################################
#
# Determine the device to be terminated.
#
if [ "$1" = "" ]; then
DEVICE=ppp0
else
DEVICE=$1
fi

######################################################################
#
# If the ppp0 pid file is present then the program is running. Stop it.
if [ -r /var/run/$DEVICE.pid ]; then
kill -INT `cat /var/run/$DEVICE.pid`
#
# If the kill did not work then there is no process running for this
# pid. It may also mean that the lock file will be left. You may wish
# to delete the lock file at the same time.
if [ ! "$?" = "0" ]; then
rm -f /var/run/$DEVICE.pid
echo "ERROR: Removed stale pid file"
exit 1
fi
#
# Success. Let pppd clean up its own junk.
echo "PPP link to $DEVICE terminated."
exit 0
fi
#
# The ppp process is not running for ppp0
echo "ERROR: PPP link is not active on $DEVICE"
exit 1

 

3、使用方法

將以上的四個指令碼檔案賦予執行許可權,並使用root許可權執行

./ppp-of /dev/ttyUSB1 115200  chat-script(具體路徑)

使用ifconfig檢視撥號的結果

4、附上一個自己寫的指令碼,其中呼叫的以上的撥號指令碼

#! /bin/sh
WR="/home/marsboard/pppd-net"

# $1 串列埠號 $2波特率 $3chat指令碼 $4 ppp-on日誌
${WR}/ppp-on $1 $2 ${WR}/$3 > ${WR}/$4 &
sleep 8

# 從ppp-on日誌中獲取撥號資訊
INTERFACENAME="Using interface"
ADDRESSIPNAME="local IP address"
GATEWAYNAME="remote IP address "

INTERFACE=`grep "$INTERFACENAME" ${WR}/$4|awk '{print $3}'`
ADDRESSIP=`grep "$ADDRESSIPNAME" ${WR}/$4|awk '{print $4}'`
GATEWAYIP=`grep "$GATEWAYNAME" ${WR}/$4|awk '{print $4}'`

# 判斷撥號是否成功
for n in `seq 3`
do
ping -c 1 ${ADDRESSIP} -I ${INTERFACE} >/dev/null 2>&1
if [ $? -eq 0 ]
then
echo "ppp Successed!!"
echo "${INTERFACE}, ${ADDRESSIP}, ${GATEWAYIP}" 
return
fi
done
echo "ppp Failed!!"

相關文章