Useful Scripts
From DD-WRT Wiki
You are here: DD-WRT wiki mainpage / Scripting / Useful Scripts
Certain scripts can enhance the function of your router with DD-WRT, giving it more features or customizing it towards your needs.
To find out how to load scripts onto the router, see Startup Scripts.
Modifying $PATH at Startup
This will add whatever paths you want for $PATH and $LD_LIBRARY_PATH before the default system path. Change the paths to whatever you like. Have a good reason for doing this, it should be considered a hack until the feature is implemented permanently.
rm -f /tmp/newProfile head -n1 /etc/profile | sed s!=!=/mmc/bin:/whatever/bin:! >> /tmp/newProfile tail -n1 /etc/profile | sed s!=!=/mmc/lib:/whatever/lib:! >> /tmp/newProfile mount --bind /tmp/newProfile /etc/profile
If you're adding /mmc/lib before the system library, in some circumstances you'll also need to do this on startup (after ensuring that the ldconfig on /mmc is up to date and happy):
mount --bind /mmc/etc/ld.so.conf /etc/ld.so.conf mount --bind /mmc/etc/ld.so.cache /etc/ld.so.cache
Note: Only do this if you're receiving segmentation faults or your applications are failing to run, and even then only if you feel that this hack is imperative. Also note that if you're attempting this with Optware, the files are ld-opt.so.conf and ld-opt.so.cache
Another alternative to the above mentioned way of altering things is to simply copy /etc/profile to /jffs/etc, change PATH and LD_LIBRARY_PATH and bind the profile to the original location.
mkdir /jffs/etc cp /etc/profile /jffs/etc/profile cd /jffs/etc vi profile (change everythings that suite your needs and save it with :x)
Afterward put the line below inside a startup script
mount --bind /jffs/etc/profile /etc/profile
Make sure you're familiar with what you're doing before attempting this, if you end up seeing a lot of segmentation faults when running things like ls, cat, cp, etc, than you'll want to either adjust the above commands, or else put those things into a script and run them manually when you enter your shell.
LED Scripts
The example LED scripts below are written using the GPIO info for the Linksys WRT. Remember to change them for whatever router you have.
You can't use the GPIOS on Atheros chips (Fonera, Meraki, etc.) without PROC_GPIO or some other utility. PROC_GPIO is a driver, and thus it must be compiled for your specific kernel. Broadcom routers do not need an external driver to drive GPIOs.
GPIO Info for Linksys WRT
Pin Direction Name Use GPIO 0 Output WLAN LED (LED - wireless) GPIO 1 Output POWER LED (LED - power) GPIO 2 Output ADM_EECS (LED - white, Cisco button v. 3.0+) GPIO 3 Output ADM_EESK (LED - amber, Cisco button v. 3.0+) GPIO 4 Input ADM_EEDO (Button - Cisco Button v. 3.0+) GPIO 5 Output ADM_EEDI (Unknown) Seems to cycle all LED colors disabled. GPIO 6 Input RESET (Button - reset button) GPIO 7 Output DMZ LED (LED - DMZ)
GPIO Info for Linksys WRT150N v1.1 (dd-wrt.v24_mini_generic)
Here is a short summary of my experiments with WRT150N v1.1 on dd-wrt.v24_mini_generic firmware. WRT150N has a SECURITY LED (the most right LED)
root@DD-WRT:~# gpio enable 5 #(SECURITY LED - off - green) root@DD-WRT:~# gpio disable 5 #(SECURITY LED - on - green) root@DD-WRT:~# gpio disable 3 #(SECURITY LED - on - amber) root@DD-WRT:~# gpio enable 3 #(SECURITY LED - off - amber)
When you switched to gpio disable 3 (SECURITY LED - on - amber)
root@DD-WRT:~# gpio enable 5 #(SECURITY LED - will give you amber) root@DD-WRT:~# gpio disable 5 #(SECURITY LED - will give you amber bright)
GPIO Info for Linksys WRT610N v2.0
It should also work for the v1.0. These commands concerns the little LED near the button.
Pin Direction Name Use GPIO 0 Output SES LED (Security LED - Amber) GPIO 3 Output SES LED (Security LED - Blue)
GPIO Info for Linksys WRTSL54GS
This is for the WRTSL54GS model only.
Pin Direction Name Use GPIO 5 Output SES LED (Cisco white LED) GPIO 7 Output SES LED (Cisco amber LED)
GPIO Info for Buffalo WHR
Pin Direction Use GPIO 0 Input AOSS button GPIO 1 Output Bridge LED GPIO 2 Output WLAN LED GPIO 3 Output Extra LED between bridge and WLAN GPIO 4 Input Reset button GPIO 5 Input Bridge/auto switch GPIO 6 Output AOSS LED GPIO 7 Output DIAG LED GPIO 8 n/a Unkown/none GPIO 9 Output Power LED
GPIO Info for LaFonera 2100
Pin Use 0 TP3 1 pin 5 of SW1 2 WLAN LED 3 pin 1 of SW1 4 pin 2 of SW1 5 Reset (!) 6 Reset button 7 pin 6 of SW1
La Fonera 2200
2 WIFI LED contact at bottom of local resistor 5 Reset! (Can be used as a GPIO, but you lose reset functionality) This is the line closest to the RP4 component (next to 3 other lines, GPIOS 6, 2, and 7) Cut the trace and use the end closest to the CPU as a GPIO. 6 Reset button (other end of button is VDD, (3.3 V)) remove nearby capacitor 7 Power LED contact at bottom of local resistor
La Fonera 2201
1 WLAN Orange LED 2 WLAN Green LED 4 Power Green LED 7 Power Orange LED
GPIO Button Wifi Toggle D-Link DIR-300
This script will enable the button on the righte side to act as a wifitoggle. on press the button-led will light up
- RED, when wifi is going to be disabled. wifi-led on the front will go out.
- BLUE, when wifi is going to be enabled again. wifi-led on the front will light up.
#!/bin/sh /sbin/gpio enable 4 echo "0" > /proc/gpio/4_out echo "0" > /proc/gpio/4_in while : ; do WIFI=`nvram get ath0_net_mode` sleep 1; if [ "$(cat /proc/gpio/4_in )" = "1" ]; then if [ "$WIFI" == "disabled" ]; then /sbin/gpio enable 1 nvram set ath0_net_mode=mixed /sbin/ifconfig ath0 up /sbin/gpio enable 2 echo "0" > /proc/gpio/4_in sleep 3 /sbin/gpio disable 1 else /sbin/gpio enable 3 nvram set ath0_net_mode=disabled /sbin/ifconfig ath0 down /sbin/gpio disable 2 echo "0" > /proc/gpio/4_in sleep 3 /sbin/gpio disable 3 fi fi done &
GPIO Button Wifi Toggle D-Link DIR-615 Rev C2
This script will enable the button on the right side to toggle the wireless status between on and off and to give an indication using the right blue LED on the button.
- LED ON, when wireless is turned on.
- LED OFF, when wireless is turned off.
LED assignment can be changed by settings GPIO variable with one of the LED constants.
Wireless start state can be configured using disableWifiOnStart.
#!/bin/sh # LED constants SIDE_LED=3 POWER_GREEN_LED=16 POWER_ORANGE_LED=1 WAN_GREEN_LED=4 WAN_ORANGE_LED=15 # Set the LED to turn on/off GPIO=$SIDE_LED # Set whether to enable/disable wireless on start disableWifiOnStart=1 # Disable wireless on start accorindg to disableWifiOnStart setting if [ $disableWifiOnStart == 1 ];then logger -s -p local0.notice -t WirelessToggle "Turning off wireless on start" /sbin/ifconfig ath0 down /sbin/gpio enable $GPIO fi # Generate SESButton script and make it executable logger -s -p local0.notice -t WirelessToggle "Generating SESButton script" mkdir /tmp/etc/config/ echo "if [ \`ifconfig | grep ath0\` == "" ]; then logger -s -p local0.notice -t WirelessToggle \"Current wireless status: Off, Turning wireless on...\" /sbin/ifconfig ath0 up /sbin/gpio disable $GPIO else logger -s -p local0.notice -t WirelessToggle \"Current wireless status: On, Turning wireless off...\" /sbin/ifconfig ath0 down /sbin/gpio enable $GPIO fi " > /tmp/etc/config/wifi_toggle.sesbutton chmod +x /tmp/etc/config/wifi_toggle.sesbutton logger -s -p local0.notice -t WirelessToggle "SESButton script generated and ready for use"
GPIO Info D-Link DIR-320
Pin Direction Use GPIO 0 Output (LED - WIRELESS) GPIO 1 Output (LED - STATUS) GPIO 3 Output (LED - RED) GPIO 4 Output (LED - BLUE) GPIO 5 Output (LED - USB) GPIO 6 Input (Button on the right)
For GPIO information, send a private message to DD-WRT user "meltyblood"
Display Load via LED (load.sh)
- Uses front button LED to display current load on router.
- For WRT54G/GL/GS
#!/bin/sh gpio="gpio" amber=3 white=2 delay=3 meltdown=400 overload=100 highload=70 medload=30 while sleep $delay;do set -- $(cat /proc/loadavg) load="${1%.*}${1#*.}" if [ $load -gt $meltdown ];then $gpio disable $amber usleep 50000 $gpio disable $white usleep 50000 reboot elif [ $load -gt $overload ];then $gpio disable $amber usleep 50000 elif [ $load -gt $highload ];then $gpio disable $amber usleep 12500 $gpio enable $amber usleep 12500 $gpio disable $amber usleep 12500 $gpio enable $amber usleep 12500 $gpio disable $amber usleep 12500 $gpio enable $amber usleep 12500 elif [ $load -gt $medload ];then $gpio enable $amber $gpio disable $white usleep 25000 $gpio enable $white usleep 25000 $gpio disable $white usleep 25000 $gpio enable $white usleep 25000 else $gpio disable $white usleep 50000 $gpio enable $white usleep 50000 fi done
Modified Script for simple display of cpu usage/load -- I use the power LED Low activity/idle (led off), medium (short flashes), high (long flashes), max (led on solid)
#!/bin/sh gpio="gpio" #This is the LED to flash led=0 extreme=110 high=75 med=35 while [ 0 ];do set -- $(cat /proc/loadavg) load="${1%.*}${1#*.}" counter=10 if [ $load -gt $extreme ];then $gpio disable $led sleep 8 elif [ $load -gt $high ];then while [ $counter -gt 0 ];do usleep 200000 $gpio disable $led usleep 800000 $gpio enable $led let counter-=1 done elif [ $load -gt $med ];then while [ $counter -gt 0 ];do usleep 800000 $gpio disable $led usleep 200000 $gpio enable $led let counter-=1 done else $gpio enable $led sleep 8 fi done
WDS link and/or associated wireless clients
- illuminates front button LED white when able to ping the gateway
- illuminates front button LED amber when wireless clients are connected
- illuminates both colors on the button when both conditions are true
- no light when neither condition is true
- developed / tested on a WRT54G-TM
GATEWAY=`ip route | awk '/default via/ {print }'` WDS_LINK_ACTIVE=false ASSOC_CLIENTS=false LOOP=0 [ `sh -c "ps | grep | grep -v grep -c"` -gt 1 ] && echo Already running && exit while sleep 1 do [ $LOOP -lt 300 ] && LOOP=$(( $LOOP + 1 )) || LOOP=1 while ! $WDS_LINK_ACTIVE do sleep 5 ping -c 1 $GATEWAY >/dev/null && WDS_LINK_ACTIVE=true done [ $LOOP -eq 1 ] && { ping -c 1 $GATEWAY >/dev/null || WDS_LINK_ACTIVE=false } [ -z $(wl -i `nvram get wl0_ifname` assoclist) ] && ASSOC_CLIENTS=false || ASSOC_CLIENTS=true $WDS_LINK_ACTIVE && gpio disable 2 || gpio enable 2 $ASSOC_CLIENTS && gpio disable 3 || gpio enable 3 done
WLAN Status (wlan.sh)
Works on k2.4 and k2.6
- Uses front button LED to show WLAN state. Amber LED indicates one or more associated clients, white LED flashes when data is sent over WLAN.
#!/bin/sh I=`nvram get wl0_ifname` while sleep 1; do if [ -z `wl -i $I assoclist` ]; then XFER=`ifconfig $I|grep bytes` if [ "$XFER" != "$PXFER" ]; then LED='gpio disable 3 ; gpio disable 2' PXFER=$XFER else LED='gpio disable 3 ; gpio enable 2' fi else LED='gpio enable 3 ; gpio enable 2' fi if [ "$LED" != "$PLED" ]; then eval $LED PLED=$LED fi done
WLAN Status (wlan.sh) - Buffalo Routers
- AOSS LED to show WLAN is associated with clients.
- Bridge LED flashes when data is transmitted over WLAN.
#!/bin/sh I=`nvram get wl0_ifname` while sleep 1; do if [ -z `wl -i $I assoclist` ]; then XFER=`ifconfig $I|grep bytes` if [ "$XFER" != "$PXFER" ]; then LED='gpio disable 1 ; gpio enable 1 ; gpio disable 6' PXFER=$XFER else LED='gpio disable 6' fi else LED='gpio enable 6' fi if [ "$LED" != "$PLED" ]; then eval $LED PLED=$LED fi done
WLAN Client Mode Status
Works on k2.4 and k2.6
Works on Repeater Bridge as well
- White LED if we can ping the gateway
- Orange LED if associated to an AP, but pinging fails.
#!/bin/sh AMBER='gpio disable 3 ; gpio enable 2' WHITE='gpio enable 3 ; gpio disable 2' BLACK='gpio enable 3 ; gpio enable 2' PACKETS='1' INTERVAL='10' trap lightsoff 1 2 3 6 14 15 lightsoff() { gpio enable 3 ; gpio enable 2 ; exit 1 } while true ; do if [ -z $(wl -i `nvram get wl0_ifname` assoclist) ]; then TARGET=`ip route | awk '/default via/ {print }'` RET=`ping -c $PACKETS $TARGET 2> /dev/null | awk '/packets received/ {print }'` if [ "$RET" -eq "$PACKETS" ]; then LED=$WHITE else LED=$AMBER fi else LED=$BLACK fi if [ "$LED" != "$PLED" ]; then eval $LED PLED=$LED fi sleep $INTERVAL done
WLAN Disable Radio If No Clients Connected
This is a cron job that will run every hour and turn off the radio if no clients are connected as requested here.
0 * * * * root I=`nvram get wl0_ifname`;[ -z `wl -i $I assoclist` ] && wl -i $I radio off
Show VPN status/activity with SES/Cisco LED
I worked out this little script out for my WRT54G-TM and WRT54GL and I thought I would share here since its based from examples shown on this forum and the wiki.
The script requires that you set 2 options in your vpn config file:
status /path/to/file (example: /tmp/vpn-status) status-version 2
For activity it parses the info in /proc/net/dev
Be sure to edit the first 2 lines (VPN_STATUS= and VPN_DEV=) of this script to match your settings.. then Paste the following into your Startup script. Code:
vpn_leds() { VPN_STATUS=/tmp/vpn-status VPN_DEV=tap0 # make sure status file exists [ ! -f "$VPN_STATUS" ] && return 1 # Set initial Cisco/SES Led mode AMBER='gpio disable 3 ; gpio enable 2' WHITE='gpio enable 3 ; gpio disable 2' BLACK='gpio enable 3 ; gpio enable 2' eval $BLACK LAST_ACT=0 while [ 1 ]; do if [ $(cat "$VPN_STATUS" |grep -c "") -gt 6 ]; then # tunnel up. White LED LED=$WHITE ACT_STRING="$(cat /proc/net/dev |grep "$VPN_DEV")" if [ "$ACT_STRING" != "$LAST_ACT" ]; then LED=$AMBER LAST_ACT=$ACT_STRING else LED=$WHITE LAST_ACT=$ACT_STRING fi else # tunnel down. All leds OFF LED=$BLACK fi if [ "$LED" != "$PLED" ]; then eval $LED LAST_LED=$LED fi sleep 1 done } vpn_leds &
Reboot your router and viola!
Light off = Tunnel down
White = Tunnel up
Amber = Activity
You can change the behavior of this script by changing each LED=$COLOR line.
Response time for tunnel up/down indication for my setup is 60sec for client connect and 120sec for disconnect. I believe the disconnect response could be improved by changing your keepalive setting in your VPN config.
Mine is set to:
keepalive 10 120
This means OpenVPN will ping the client every 10sec and assume the client has disconnect if no reply is received within 120sec. lowering the last value should improve the response time but be careful not to lower it too much as not to cause connection drops due to timeout
Hope this helps,
-onemyndseye
Original Post
Update: Fun with egrep!
Here is an updated version that will monitor for activity on ANY tap or tun device that exists. Still only showing up/down status for 1 tunnel
vpn_leds() { VPN_STATUS=/tmp/vpn-status # make sure status file exists [ ! -f "$VPN_STATUS" ] && return 1 # Set initial Cisco/SES Led mode AMBER='gpio disable 3 ; gpio enable 2' WHITE='gpio enable 3 ; gpio disable 2' BLACK='gpio enable 3 ; gpio enable 2' eval $BLACK LAST_ACT="$(cat /proc/net/dev |egrep "tap|tun")" while [ 1 ]; do if [ $(cat "$VPN_STATUS" |grep -c "") -gt 6 ]; then # tunnel up. White LED LED=$WHITE ACT_STRING="$(cat /proc/net/dev |egrep "tap|tun")" if [ "$ACT_STRING" != "$LAST_ACT" ]; then LED=$AMBER LAST_ACT=$ACT_STRING else LED=$WHITE LAST_ACT=$ACT_STRING fi else # tunnel down. All leds OFF LED=$BLACK fi if [ "$LED" != "$PLED" ]; then eval $LED LAST_LED=$LED fi sleep 1 done } vpn_leds &
USB Disc Mount Status and Umount Button (DIR-320 running v24-sp2 mini-usb-ftp)
- SES red LED to indicate disc mounted
- SES button to umount disc
- SES blue LED to indicate umounting proccess
Script /jffs/etc/config/mount_status.startup (disc mount status)
#!/bin/sh mp="/`nvram get usb_mntpoint`" RED_ON='gpio disable 3' RED_OFF='gpio enable 3' while sleep 1; do if [ "`mount | grep $mp`" ]; then LED=$RED_OFF else LED=$RED_ON fi if [ "$LED" != "$PLED" ]; then eval $LED PLED=$LED fi done
Script /jffs/etc/config/mount.sesbutton
#!/bin/sh mp="/`nvram get usb_mntpoint`" proftpd_enable="`nvram get proftpd_enable`" RED_ON='gpio disable 3' RED_OFF='gpio enable 3' BLUE_ON='gpio disable 4' BLUE_OFF='gpio enable 4' if [ "`mount | grep $mp`" ]; then $RED_OFF $BLUE_ON if [ "$proftpd_enable" == "1" ]; then killall proftpd fi umount $mp if [ "$proftpd_enable" == "1" ]; then proftpd fi fi if [ "`mount | grep $mp`" ]; then $RED_ON else $RED_OFF fi $BLUE_OFF
Display signal strength over the SES light - Linksys routers
Use this script If you want to catch a better signal without computers.
Script not work in dd-wrt micro version
Linksys routers where this script will work :
- WRT54GL v1.0
- WRT54GL v1.1
- WRT54G-TM
- WRT54G v4.0
- WRT54GS V4
Linksys routers where the script does not work:
- WRT54GS v6.0
- WRT54G v5
- WRTSL54GS
has not yet been tested on other models
Discuss here.
Script Version 2
Script version two show signal more precise
SIGNAL STRENGTH
- 0 blink = SNR < 9 No signal or very weak
- 1 blink = SNR 10-19
- 2 blinks = SNR 20-29
- 3 blinks = SNR 30-39
- 4 blinks = SNR 40-49
- 5 blinks = SNR 50-59 Excellent signal
- 6 blinks = SNR 60 > Very strong signal
Installation is pretty simple:
1. Go to "Administration -> Commands"
2. Paste script in "Command Shell"
3. Click on "Save Startup"
4. Reboot router
Works great in Client mode and Repeater mode
To work in AP mode, you must put the mac address
#!/bin/sh ############################################### #----Created by MOJSO-----Script version 2----# ############################################### # SIGNAL STRENGTH # 0 blink = SNR < 9 No signal or very weak # 1 blink = SNR 10-19 # 2 blinks = SNR 20-29 # 3 blinks = SNR 30-39 # 4 blinks = SNR 40-49 # 5 blinks = SNR 50-59 Excellent signal # 6 blinks = SNR 60 > Very strong signal ############################################### while sleep 3; do BLACK=`gpio enable 3 ; gpio enable 2` S=`wl rssi` #(put mac adress if in AP mod example: S=`wl rssi 00:11:22:33:44:55` ) N=`wl noise` SC=`expr $S - $N` RSC=`expr $SC / 10` if [ $RSC -eq 0 ]; then gpio enable 3 ; gpio enable 2 ; elif [ $RSC -eq 1 ]; then gpio enable 3 ; gpio disable 2 ; usleep 500000 gpio enable 3 ; gpio enable 2 ; elif [ $RSC -eq 2 ]; then gpio enable 3 ; gpio disable 2 ; usleep 500000 gpio enable 3 ; gpio enable 2 ; usleep 500000 gpio enable 3 ; gpio disable 2 ; usleep 500000 gpio enable 3 ; gpio enable 2 ; elif [ $RSC -eq 3 ]; then gpio enable 3 ; gpio disable 2 ; usleep 250000 gpio enable 3 ; gpio enable 2 ; usleep 250000 gpio enable 3 ; gpio disable 2 ; usleep 250000 gpio enable 3 ; gpio enable 2 ; usleep 250000 gpio enable 3 ; gpio disable 2 ; usleep 250000 gpio enable 3 ; gpio enable 2 ; elif [ $RSC -eq 4 ]; then gpio disable 3 ; gpio enable 2 ; usleep 250000 gpio enable 3 ; gpio enable 2 ; usleep 250000 gpio disable 3 ; gpio enable 2 ; usleep 250000 gpio enable 3 ; gpio enable 2 ; usleep 250000 gpio disable 3 ; gpio enable 2 ; usleep 250000 gpio enable 3 ; gpio enable 2 ; usleep 250000 gpio disable 3 ; gpio enable 2 ; usleep 250000 gpio enable 3 ; gpio enable 2 ; elif [ $RSC -eq 5 ]; then gpio disable 3 ; gpio enable 2 ; usleep 250000 gpio enable 3 ; gpio enable 2 ; usleep 250000 gpio disable 3 ; gpio enable 2 ; usleep 250000 gpio enable 3 ; gpio enable 2 ; usleep 250000 gpio disable 3 ; gpio enable 2 ; usleep 250000 gpio enable 3 ; gpio enable 2 ; usleep 250000 gpio disable 3 ; gpio enable 2 ; usleep 250000 gpio enable 3 ; gpio enable 2 ; usleep 250000 gpio disable 3 ; gpio enable 2 ; usleep 250000 gpio enable 3 ; gpio enable 2 ; elif [ $RSC -ge 6 ]; then gpio disable 3 ; gpio enable 2 ; usleep 250000 gpio enable 3 ; gpio enable 2 ; usleep 250000 gpio enable 3 ; gpio disable 2 ; usleep 250000 gpio enable 3 ; gpio enable 2 ; usleep 250000 gpio disable 3 ; gpio enable 2 ; usleep 250000 gpio enable 3 ; gpio enable 2 ; usleep 250000 gpio enable 3 ; gpio disable 2 ; usleep 250000 gpio enable 3 ; gpio enable 2 ; usleep 250000 gpio disable 3 ; gpio enable 2 ; usleep 250000 gpio enable 3 ; gpio enable 2 ; usleep 250000 gpio enable 3 ; gpio disable 2 ; usleep 250000 gpio enable 3 ; gpio enable 2 ; else gpio enable 3 ; fi done
Script Version 1
Installation is pretty simple:
1. Go to "Administration -> Commands"
2. Paste script in "Command Shell"
3. Click on "Save Startup"
4. Reboot router
Works great in Client mode and Repeater mode
To work in AP mode, you must put the mac address
#!/bin/sh ############Created by MOJSO#################### # White / Black / White - low signal # # Amber / Black / Amber - good signal # # Amber / White / Amber - excellent signal# ############################################ while sleep 3; do BLACK=`gpio enable 3 ; gpio enable 2` S=`wl rssi` #(put mac adress if in AP mod example: S=`wl rssi 00:11:22:33:44:55` ) N=`wl noise` SC=`expr $S - $N` RSC=`expr $SC / 10` if [ $RSC -eq 0 ]; then gpio enable 3 ; gpio enable 2 ; elif [ $RSC -eq 1 ]; then gpio enable 3 ; gpio disable 2 ; sleep 1 gpio enable 3 ; gpio enable 2 ; sleep 1 gpio enable 3 ; gpio disable 2 ; elif [ $RSC -eq 2 ]; then gpio enable 3 ; gpio disable 2 ; sleep 1 gpio enable 3 ; gpio enable 2 ; sleep 1 gpio enable 3 ; gpio disable 2 ; elif [ $RSC -eq 3 ]; then gpio enable 3 ; gpio disable 2 ; sleep 1 gpio enable 3 ; gpio enable 2 ; sleep 1 gpio enable 3 ; gpio disable 2 ; elif [ $RSC -eq 4 ]; then gpio disable 3 ; gpio enable 2 ; sleep 1 gpio enable 3 ; gpio enable 2 ; sleep 1 gpio disable 3 ; gpio enable 2 ; elif [ $RSC -eq 5 ]; then gpio disable 3 ; gpio enable 2 ; sleep 1 gpio enable 3 ; gpio enable 2 ; sleep 1 gpio disable 3 ; gpio enable 2 ; elif [ $RSC -ge 6 ]; then gpio disable 3 ; gpio enable 2 ; sleep 1 gpio enable 3 ; gpio disable 2 ; sleep 1 gpio disable 3 ; gpio enable 2 ; else gpio enable 3 ; gpio enable 2 ; fi done
Display signal strength over the Diagnostic light - Buffalo routers
Use this script If you want to catch a better signal without computers.
Script not work in dd-wrt micro version
Bufalo routers where this script will work :
- WHR-HP-G54-DD
Has not yet been tested on other models
Discuss here.
SIGNAL STRENGTH
- 0 blink = SNR < 9 No signal or very weak
- 1 blink = SNR 10-19
- 2 blinks = SNR 20-29
- 3 blinks = SNR 30-39
- 4 blinks = SNR 40-49
- 5 blinks = SNR 50-59 Excellent signal
- 6 blinks = SNR 60 > Very strong signal
Installation is pretty simple:
1. Go to "Administration -> Commands"
2. Paste script in "Command Shell"
3. Click on "Save Startup"
4. Reboot router
Works great in Client mode and Repeater mode
To work in AP mode, you must put the MAC address
#!/bin/sh ############################################### #--------------Created by MOJSO---------------# ############################################### # SIGNAL STRENGTH # 0 blink = SNR < 9 No signal or very weak # 1 blink = SNR 10-19 # 2 blinks = SNR 20-29 # 3 blinks = SNR 30-39 # 4 blinks = SNR 40-49 # 5 blinks = SNR 50-59 Excellent signal # 6 blinks = SNR 60 > Very strong signal ############################################### while sleep 3; do BLACK=`gpio enable 7` S=`wl rssi` #(put mac adress if in AP mod example: S=`wl rssi 00:11:22:33:44:55` ) N=`wl noise` SC=`expr $S - $N` RSC=`expr $SC / 10` if [ $RSC -eq 0 ]; then gpio enable 7 ; elif [ $RSC -eq 1 ]; then gpio disable 7 ; usleep 500000 gpio enable 7 ; elif [ $RSC -eq 2 ]; then gpio disable 7 ; usleep 500000 gpio enable 7 ; usleep 500000 gpio disable 7 ; usleep 500000 gpio enable 7 ; elif [ $RSC -eq 3 ]; then gpio disable 7 ; usleep 250000 gpio enable 7 ; usleep 250000 gpio disable 7 ; usleep 250000 gpio enable 7 ; usleep 250000 gpio disable 7 ; usleep 250000 gpio enable 7 ; elif [ $RSC -eq 4 ]; then gpio disable 7 ; usleep 250000 gpio enable 7 ; usleep 250000 gpio disable 7 ; usleep 250000 gpio enable 7 ; usleep 250000 gpio disable 7 ; usleep 250000 gpio enable 7 ; usleep 250000 gpio disable 7 ; usleep 250000 gpio enable 7 ; elif [ $RSC -eq 5 ]; then gpio disable 7 ; usleep 250000 gpio enable 7 ; usleep 250000 gpio disable 7 ; usleep 250000 gpio enable 7 ; usleep 250000 gpio disable 7 ; usleep 250000 gpio enable 7 ; usleep 250000 gpio disable 7 ; usleep 250000 gpio enable 7 ; usleep 250000 gpio disable 7 ; usleep 250000 gpio enable 7 ; elif [ $RSC -ge 6 ]; then gpio disable 7 ; usleep 250000 gpio enable 7 ; usleep 250000 gpio disable 7 ; usleep 250000 gpio enable 7 ; usleep 250000 gpio disable 7 ; usleep 250000 gpio enable 7 ; usleep 250000 gpio disable 7 ; usleep 250000 gpio enable 7 ; usleep 250000 gpio disable 7 ; usleep 250000 gpio enable 7 ; usleep 250000 gpio disable 7 ; usleep 250000 gpio enable 7 ; else gpio enable 7 ; fi done
Miscellaneous Scripts
Backup settings and restore them
Credit to hardwarewizard and frater
Reference Thread
#!/bin/sh ######################################################### # Script Requirements # # Files: # vars_to_skip # vars_preferred # # Programs: # curl ######################################################### ######################################################### # setup variables # # DATE - Date # MAC - Mac address # FILE - File Name Prefix # CUR_DIR - Current Directory # transfer - FTP Transfer ON/OFF (Default is OFF) # FOLDER - Location where backup scripts are stored # VARFILE - Location & Name of Temp File # TO_ALL - Location & Name of script File with all nvram variables # TO_INCLUDE - Location & Name of script File with essential nvram variables # TO_EXCLUDE - Location & Name of script File with dangerous nvram variables # TO_PREFERRED - Location & Name of script File with preferred nvram variables # ######################################################### DATE=`date +%m%d%Y` MAC=`nvram get lan_hwaddr | tr -d ":"` FILE=${MAC}.${DATE} CUR_DIR=`dirname $0` transfer=0 FOLDER=/opt/vars/backups VARFILE=/opt/tmp/all_vars TO_ALL=${FOLDER}/${MAC}.${DATE}.all.sh TO_INCLUDE=${FOLDER}/${MAC}.${DATE}.essential.sh TO_EXCLUDE=${FOLDER}/${MAC}.${DATE}.dangerous.sh TO_PREFERRED=${FOLDER}/${MAC}.${DATE}.preferred.sh ######################################################### #FTP Login information change to your info ######################################################### FTPS=ftp://192.168.1.100/backups USERPASS=user:pass ######################################################### # read command line switches # # example command lines # # ./backupvars.sh -t # # The above command with use the user and password and # server information embedded in this script. # (See FTP Login information above) # # # ./backupvars.sh -t -u user:pass -f ftp://192.168.1.100/backups # # The above command with use the user and password and # server information from the command line # ######################################################### while getopts tu:f: name do case $name in t) transfer=1;; u) USERPASS="$OPTARG";; f) FTPS="$OPTARG";; ?) printf "Usage: %s: [-t] [-u username:password] [-f ftpserver]\n" exit 2;; esac done shift $(($OPTIND - 1)) ######################################################### #create NVRAM variale list and write to /opt/tmp/all_vars ######################################################### nvram show 2>/dev/null | egrep '^[A-Za-z][A-Za-z0-9_\.\-]*=' | awk -F = '{print $1}' | sort -r -u >${VARFILE} ######################################################### # Write header to restore scripts ######################################################### echo -e "#!/bin/sh\n#\necho \"Write variables\"\n" | tee -i ${TO_EXCLUDE} | tee -i ${TO_PREFERRED} | tee -i ${TO_ALL} > ${TO_INCLUDE} ######################################################### # scan NVRAM variable list and send variable to proper # restore script ######################################################### cat ${VARFILE} | while read var do pref=0 ### replaced with next line by Andon Mančev : if echo "${var}" | grep -q -f "${CUR_DIR}/vars_to_skip" ; then if cat "${CUR_DIR}/vars_to_skip" | grep -q "${var}" ; then bfile=$TO_EXCLUDE else bfile=$TO_INCLUDE pref=`echo "${var}" | grep -cf "${CUR_DIR}/vars_preferred"` fi # get the data out of the variable data=`nvram get ${var}` # write the var to the file and use \ for special chars: (\$`") echo -en "nvram set ${var}=\"" | tee -ia ${TO_ALL} >> ${bfile} echo -n "${data}" | sed -e 's/[$`"\]/\\&/g' | tee -ia ${TO_ALL} >> ${bfile} echo -e "\"" | tee -ia ${TO_ALL} >> ${bfile} if [ ! ${pref} == 0 ]; then echo -en "nvram set ${var}=\"" >> ${TO_PREFERRED} echo -n "${data}" | sed -e 's/[$`"\]/\\&/g' >> ${TO_PREFERRED} echo -e "\"" >> ${TO_PREFERRED} fi done ######################################################### # cleanup remove /opt/tmp/all_vars # uncomment to remove file ######################################################### # rm ${VARFILE} ######################################################### # Write footer to restore script ######################################################### echo -e "\n# Commit variables\necho \"Save variables to nvram\"\nnvram commit" | tee -ia ${TO_ALL} | tee -ia ${TO_PREFERRED} | tee -ia ${TO_EXCLUDE} >> ${TO_INCLUDE} ######################################################### # Change permissions on restore scripts to make them # executable ######################################################### chmod +x ${TO_INCLUDE} chmod +x ${TO_PREFERRED} chmod +x ${TO_EXCLUDE} chmod +x ${TO_ALL} ######################################################### # Compress restore scripts and send them to ftp server ######################################################### if [ ${transfer} -ne 0 ] ; then tar cpf - -C / "${TO_INCLUDE}" 2>/dev/null | gzip -c | /opt/bin/curl -s -u ${USERPASS} "${FTPS}/${FILE}.essential.sh.tgz" -T - tar cpf - -C / "${TO_PREFERRED}" 2>/dev/null | gzip -c | /opt/bin/curl -s -u ${USERPASS} "${FTPS}/${FILE}.preferred.sh.tgz" -T - tar cpf - -C / "${TO_EXCLUDE}" 2>/dev/null | gzip -c | /opt/bin/curl -s -u ${USERPASS} "${FTPS}/${FILE}.dangerous.sh.tgz" -T - tar cpf - -C / "${TO_ALL}" 2>/dev/null | gzip -c | /opt/bin/curl -s -u ${USERPASS} "${FTPS}/${FILE}.all.sh.tgz" -T - fi
The vars_to_skip file
DD_BOARD ^board browser_method ^cfe ct_modules custom_shutdown_command ^def_ ^default_ dist_type dl_ram_addr early_startup_command ^et0 ^et1 ^ezc generate_key gozila_action gpio ^hardware ^is_ ^kernel_ lan_default ^lan_hw ^lan_ifname landevs manual_boot_nv misc_io_mode need_commit ^os_ overclocking pa0maxpwr phyid_num pmon_ver pppd_pppifname pppoe_ifname pppoe_wan_ifname primary_ifname probe_blacklist regulation_domain rescue reset_ scratch sdram ^sh_ ^skip sshd_dss_host_key sshd_rsa_host_key startup_command ^wan_default ^wan_hw ^wan_if ^wan_vport ^wandevs web_hook_libraries ^wifi_ wl0.1_hwaddr wl0.2_hwaddr wl0.3_hwaddr wl0_hwaddr wl0_ifname wl0_radioids ^wl_ ^wlan_
The vars_preferred file. This is the file you add your vars to that you want to backup.
daylight_time time_zone
this is an updated version
Clear ttraff (WAN bandwidth graph) nvram data
The ttraff daemon can fill up a couple hundred bytes of nvram space every month. This may not seem like much but nvram is only ~32KB total and is full of lots of other data. Disabling ttraff and clearing it's old nvram data is sometimes needed for devices with complex configurations, or to keep the router stable. This script will clear all of ttraff's traffic data from nvram whereas using the ttraff GUI button to delete it still leaves the current month's variable.
for i in `nvram show | grep traff- | cut -f1 -d=""`; do nvram unset $i; done
Compress the Firewall Script (to reduce nvram usage)
If you have a large firewall script you can use this script to compress it with gzip to use less nvram space. See this thread for full usage info.
# Compress Firewall nvram set pH_fw="`nvram get rc_firewall | gzip | uuencode -m /dev/stdout`" nvram set rc_firewall="nvram get pH_fw | uudecode -o /tmp/pH_fw.gz;gunzip /tmp/pH_fw.gz;chmod +x /tmp/pH_fw;/tmp/pH_fw" nvram show >/dev/null
# Decompress Firewall nvram get pH_fw | uudecode -o /tmp/pH_fw.gz nvram unset pH_fw gunzip /tmp/pH_fw.gz nvram set rc_firewall="`cat /tmp/pH_fw`" nvram show >/dev/null
# Editing the Firewall vi /tmp/pH_fw # finish editing with vi before running the rest nvram set rc_firewall="`cat /tmp/pH_fw`" nvram show >/dev/null
Web Server Wake-up
- Wakes up your web server when the router receives a request from the internet. Credits from here.
Please note: syslogd needs to be on, logging enabled, with log level set high, and "accepted" on. Following the example script, replace target and MAC values with those of your LAN web server's network information and for "$WOL -i xxx.xxx.xxx.255", replace xxx.xxx.xxx.255 with your LAN network broadcast address.
#!/bin/sh INTERVAL=5 NUMP=3 OLD="" WOL=/usr/sbin/wol TARGET=192.168.1.100 MAC=00:00:00:00:00:00 LOGFILE="/tmp/www/wol.log" while sleep $INTERVAL;do NEW=`awk '/ACCEPT/ && /DST='"$TARGET"'/ && /DPT=80/ {print }' /var/log/messages | tail -1` SRC=`awk -F'[=| ]' '/ACCEPT/ && /DST='"$TARGET"'/ && /DPT=80/ {print }' /var/log/messages | tail -1` LINE=`awk '/ACCEPT/ && /DST='"$TARGET"'/ && /DPT=80/' /var/log/messages` if [ "$NEW" != "" -a "$NEW" != "$OLD" ]; then echo "$SRC $LINE" >> $LOGFILE RET=`ping -c $NUMP $TARGET 2> /dev/null | awk '/packets received/ {print }'` if [ "$RET" -ne "$NUMP" ]; then echo "$SRC causes WOL at" `date` >> $LOGFILE $WOL -i 192.168.1.255 -p 7 $MAC >> $LOGFILE sleep 5 fi OLD=$NEW fi done
Auto Random MAC Address
- This script will change your eth1 MAC address to a random address, then it will apply it to the system and restart the interfaces.
#!/bin/ash MAC=`(date; cat /proc/interrupts) | md5sum | sed -r 's/^(.{10}).*$/\1/; s/([0-9a-f]{2})/\1:/g; s/:$//;'` echo "00:${MAC}" ifconfig eth1 hw ether 00:${MAC} nvram set def_hwaddr="00:${MAC}" nvram set wan_hwaddr="00:${MAC}" stopservice wan startservice wan
You may wish to also download curl (see ipkg), and use it to restart your modem, as some MAC changes may not reflect until your modem "sees" a new address, and they typically only do this when starting up.
Note: curl is sometimes problematic to install. You should use ipkg -force-depends
An example, to restart a Motorola Surfboard SB4100 cable model is:
curl -s -d "BUTTON_INPUT=Restart+Cable+Modem" http://192.168.100.1/configdata.html
To restart a Motorola SB5101:
curl -d ResetReq=1 http://192.168.100.1/goform/RgConfig
I added the following lines to the end of the above to restart a Motorola SB5120 (no curl required!!) and reboot. Running this script in cron, and my ISP won't automatically recover without the following:
nvram commit & sleep 5 && wget http://192.168.100.1/reset.htm?reset_modem=Restart+Cable+Modem reboot
Don't know the reason but Motorola SB5101 only re-started with the two following lines:
curl -v -d "RestoreFactoryDefault=1&ResetReq=1" http://192.168.100.1/goform/RgConfig curl -d ResetReq=1 http://192.168.100.1/goform/RgConfig
Wireless Network Scanner (awk -f scanner)
##################### cat - > scanner # Show scanresults in consistent order with graphical bars. # To be run via telnet to WRT54g running modified firmware. # Do the following. Use your own router address instead of 192.168.1.1 on the following lines # Login via telnet: # telnet 192.168.1.1 # a simple test to make sure you can run this script, type: # wl scan; wl scanresults # and make sure you can run those commands. If not this program will not work. # If you succeeded with the scanresults then # copy and paste this entire text into the terminal window # (the cat - > scanner line will copy the rest of the file into a file named 'scanner') # and then hit return and then ctrl-c to close the file. # then just run script by typing the following line: # awk -f scanner # # I hereby release this into the public domain. Justin Jones, 2005 # # Jan. '07 corrected bug from '06 improvement. BEGIN{ IGNORECASE = 1; command = "wl scan 2> /dev/null ; wl scanresults 2> /dev/null"; red = "\x1b[31m"; green = "\x1b[32m"; greenback="\x1b[42m"; yellow = "\x1b[33m"; cyan = "\x1b[36m"; blue = "\x1b[34m"; blueback = "\x1b[44m"; white = "\x1b[37m"; whiteback = "\x1b[47m"; reset = "\x1b[0m"; underscore = "\x1b[4m"; clear = "\x1b[2J"; home = "\x1b[0;0H"; erase2end = "\x1b[K"; cName = white; cSignal = green; cNoise = red; cCaps = green; cStrengthLow = blue blueback; cChannel = green; cStrengthMed = white whiteback; cStrengthHi = green greenback; cStrengthAged = red; print clear; for(;;) { while (command|getline) { if(/^SSID/) { name = ; rssi = ;noise= ; rssi=""; noise="";channel="";bssid="";caps=""} if(/^Mode/) {rssi = ;noise= ; channel = } if(/^BSSID/) {bssid = ; caps = " "" "" "" "" "" " } if(/^Supported/) { name[bssid] = name rssi[bssid] = rssi noise[bssid]= noise channel[bssid] = channel caps[bssid] = caps } } close(command) printf home; ln = 0; print white " Name BSSID Signal Noise Channel Type"; for (x in name) { { #arbitrary strength calc through trial and error... modify as you wish: sigstrength = ((rssi[x] - noise[x])*1.5) + ((rssi[x] +90)*1.5); if (sigstrength <1) sigstrength=0; cStrength = cStrengthLow; if(sigstrength>4) cStrength = cStrengthMed; if(sigstrength>7) cStrength = cStrengthHi; if(age[x]=0) cStrength = cStrengthAged; fmt = "%s%-15s %s%0"sigstrength"d "reset erase2end "\n %s %s%-4d %s%-4d %s%-4d %s%2s %s%10s " reset erase2end "\n" erase2end "\n"; printf fmt, cName,name[x],cStrength,0,x,cSignal,rssi[x],cNoise,noise[x],cChannel, channel[x],cCaps,caps[x]; rssi[x] = "-1000 xxxx"; ln++; } } if (ln ==0) print red "No Results - Do you have wl scan capability? \nThis program depends on 'wl scan; wl scanresults' to run. Hit ctrl-c to stop." print erase2end; } }
Wireless Network Scanner (working on DD-WRT v24)
I took the above script and tweaked it to work in DD-WRT v24 firmware, with the "wl" command.
To run just copy and paste in a console (telnet or ssh) or save as a "scanner.sh" and run as ./scanner.
#!/bin/sh awk -F"[][]" ' BEGIN{ IGNORECASE = 1; command = "site_survey 2>&1"; red = "\x1b[31m"; green = "\x1b[32m"; greenback="\x1b[42m"; yellow = "\x1b[33m"; cyan = "\x1b[36m"; blue = "\x1b[34m"; blueback = "\x1b[44m"; white = "\x1b[37m"; whiteback = "\x1b[47m"; reset = "\x1b[0m"; underscore = "\x1b[4m"; clear = "\x1b[2J"; home = "\x1b[0;0H"; erase2end = "\x1b[K"; cName = white; cSignal = green; cNoise = red; cCaps = green; cStrengthLow = blue blueback; cChannel = green; cStrengthMed = white whiteback; cStrengthHi = green greenback; cStrengthAged = red; print clear; for(;;) { while (command|getline) { if ( == "") continue; bssid=; name[bssid] = ; rssi[bssid] = ; noise[bssid]= ; channel[bssid] = ; caps[bssid] = ; age[bssid] = 1; } close(command); printf home; ln = 0; print white " Name BSSID Signal Noise Channel Type"; for (x in name) { #arbitrary strength calc through trial and error... modify as you wish: sigstrength = ((rssi[x] - noise[x])*1.5) + ((rssi[x] +90)*1.5); if (sigstrength <1) sigstrength=0; cStrength = cStrengthLow; if(sigstrength>4) cStrength = cStrengthMed; if(sigstrength>7) cStrength = cStrengthHi; if(age[x]=0) cStrength = cStrengthAged; fmt = "%s%-15s %s%0"sigstrength"d "reset erase2end "\n %s %s%-4d %s%-4d %s%-4d %s%2s " reset erase2end "\n" erase2end "\n"; printf fmt, cName,name[x],cStrength,0,x,cSignal,rssi[x],cNoise,noise[x],cChannel, channel[x],cCaps,caps[x]; rssi[x] = "-100 xxxx"; ln++; } if (ln ==0) print red "No results - Do you have survey capability? \nThis program depends on site_survey to run. Hit ctrl-c to stop."; print erase2end; } } '
Name-based WOL (wake.sh)
- Enables you to power on a LAN computer by name instead of IP address/MAC, based on DHCP lease table (mandatory).
Usage: /path/to/wake.sh <hostname>
(default hostname is desktop)
STATION=mm WOL=/usr/sbin/wol STATICS=/tmp/udhcpd.statics DEV=br0 if [ -n "" ]; then STATION= fi while read LINE do IP=`echo $LINE | awk '{print }'` MAC=`echo $LINE | awk '{print }'` FOUND=`ip neigh | grep "$IP.*REACHABLE"` if [ -z "$FOUND" ]; then echo Creating ARP entry for $IP $MAC ip neigh add $IP lladdr $MAC dev $DEV nud reachable 2> /dev/null ip neigh change $IP lladdr $MAC dev $DEV nud reachable 2> /dev/null fi done < $STATICS LEASE=`grep "\b$STATION\b$" $STATICS` if [ -n "$LEASE" ]; then IP=`echo $LEASE | awk '{print }'` MAC=`echo $LEASE | awk '{print }'` $WOL -i $IP $MAC else echo Unable to find \"$STATION\" in DHCP static file $STATICS, please use \" \<hostname\>\" fi
Automatic Connection Repair (always_on.sh)
- Pings your default gateway every time and force a DHCP renew if no packets are received.
Usage: /path/to/always_on.sh &
#!/bin/sh INTERVAL=10 PACKETS=1 UDHCPC="udhcpc -i vlan1 -p /var/run/udhcpc.pid -s /tmp/udhcpc" IFACE=vlan1 ME=`basename ` RUNNING=`ps | awk '/'"$ME"'/ {++x}; END {print x+0}'` if [ "$RUNNING" -gt 3 ]; then echo "Another instance of \"$ME\" is running" exit 1 fi while sleep $INTERVAL do TARGET=`ip route | awk '/default via/ {print }'` RET=`ping -c $PACKETS $TARGET 2> /dev/null | awk '/packets received/ {print }'` if [ "$RET" -ne "$PACKETS" ]; then echo "Ping failed, releasing IP address on $IFACE" #send a RELEASE signal kill -USR2 `cat /var/run/udhcpc.pid` 2> /dev/null #ensure udhcpc is not running killall udhcpc 2> /dev/null echo "Renewing IP address: $IFACE" $UDHCPC echo "Waiting 10 s..." sleep 10 else echo "Network is up via $TARGET" fi done
- The following version will work even on resource-starved Linksys WRT54G v8, which lacks most programs needed by the script above. To use it, just add this code to DD-WRT's startup script using the web interface.
INTERVAL=10 while true; do while [ \! $gw ]; do sleep 30 route -n >/tmp/routes while read dest gw foo; do if [ $dest = "0.0.0.0" ]; then break fi done </tmp/routes done logger "auto-repair: default gateway is $gw" while ping -qc 2 $gw >/dev/null ; do sleep $INTERVAL done logger "auto-repair: gateway down, restarting WAN" kill -USR1 `cat /var/run/udhcpc.pid` unset gw done &
Modifying $PATH Manually (path.sh)
- Enables adjustment of paths on a per-use basis (i.e. when you're running a terminal and need the new paths, run this script.).
#!/bin/sh export PATH=$PATH:/mmc/bin:/whatever/bin export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/mmc/lib:/whatever/lib
Alternatively, if you want to give priority to you're personally installed applications (i.e. you've installed a more robust version of grep, and want to use it by default), add the new paths before $PATH and $LD_LIBRARY_PATH, as shown below.
#!/bin/sh export PATH=/mmc/bin:/whatever/bin:$PATH export LD_LIBRARY_PATH=/mmc/lib:/whatever/lib:$LD_LIBRARY_PATH
View Logfile in Browser without Local Syslogd (log.sh)
- View the last 1000 lines from your router's logfile in your browser without a locally running syslogd (i.e. Kiwi)
First Method: Script Generated Live-content
Initial post in German forum: SOLVED: messages (logdatei) formatiert über browser aufrufen)
#!/bin/sh echo '<HTML><HEAD><TITLE>Logfile</TITLE></HEAD>' echo '<BODY>'<br />nvram get router_name echo ' Logfile:<br><pre>' /usr/bin/tail -n 1000 /var/log/messages echo '</BODY></HTML>'
To use this script you first need to enable syslog on your router without stating an IP. Then the log will be saved in /var/log/messages. You can do this under Administration->Services and then scroll down to the "System Log" section. Click "Enable" and leave "Remote Server" empty. After you saved the script under /tmp/www/ as "log.sh" you must mark it as executable with "chmod +x /tmp/www/log.sh". You can do that by saving the following in your startup script:
echo -en "#!/bin/sh\necho '<HTML><HEAD><TITLE>Logfile</TITLE></HEAD>'\necho '<BODY>'\nnvram get router_name\necho ' Logfile:<br><pre>'\n/usr/bin/tail -n 1000 /var/log/messages\necho '</BODY></HTML>'" > /tmp/www/log.sh
To view the log in your browser point it to "http://<routerip>/user/log.sh"
It appears that the above method doesn't work under some versions of v24 as shell scripts need to be created in the cgi-bin folder in order for the webserver to execute them.
If you find the previous startup script doesn't work, try the following:
mkdir /tmp/www/cgi-bin echo -en "#!/bin/sh\necho '<HTML><HEAD><TITLE>Logfile</TITLE></HEAD>'\necho '<BODY>'\nnvram get router_name\necho ' Logfile:<br><pre>'\n/usr/bin/tail -n 1000 /var/log/messages\necho '</BODY></HTML>'" > /tmp/www/cgi-bin/log.sh chmod +x /tmp/www/cgi-bin/log.sh
and use http://<routerip>/user/cgi-bin/log.sh to access it.
Second Method: Static Generated HTML
Note that it is reported that script-generated content will not be delivered by the web server in v24-RC4 and v24-RC5, maybe other versions are affected too (see User-HTML (skript generiert) funzt nicht :( in the German forum). If you just get an empty page if using the first method you may use this workaround:
echo -en "#!/bin/sh\nrm /tmp/www/syslog.html\necho '<HTML><HEAD><TITLE>Logfile (Generated: ' >> /tmp/www/syslog.html\ndate >> /tmp/www/syslog.html\necho ')</TITLE></HEAD><BODY>' >> /tmp/www/syslog.html\nnvram get router_name >> /tmp/www/syslog.html\necho ' Logfile:<br><pre>' >> /tmp/www/syslog.html\n/usr/bin/tail -n 1000 /var/log/messages >> /tmp/www/syslog.html\necho '</BODY></HTML>' >> /tmp/www/syslog.html" > /tmp/www/log_gen.sh
chmod +x /tmp/www/log_gen.sh </pre>
Save the above code to your startup script and create a cron job for it. To generate a HTML log every 15 minutes you could use this job:
*/15 * * * * root /tmp/www/log_gen.sh
Your router's syslog is now available on http://<routerip>/user/syslog.html and will be updated every 15 minutes (or whatever you've set in the cron job).
Speak Your Signal Strength
I use my WRT in client mode to connect to an access point, but I don't have a particularly good signal quality and I often need to re adjust the position of the WRT and its antenna. Unfortunately my computer is not in sight of the WRT and I had to keep going backwards and forwards from my computer to the WRT making adjustments then checking the signal strength on the screen of my computer. This can take ages to to set up properly, so I decided to get my computer to use the "festival" speech synthesis program to tell me what the current signal level is.
#! /bin/bash # Use "festival" to say out loud how much signal strength we have # The IP address of the WRT ip_addr="192.168.1.1" # The username and password for the WRT user="root" pass="admin" # Tempory file used to hold the data from the WRT tmp_file=/tmp/wrt.status echo echo "The signal level is:-" echo echo "The signal level is" | festival --tts while true ; do wget --http-user=$user --http-password=$pass http://$ip_addr/Status_Wireless.live.asp -O $tmp_file -o /dev/null signal=`awk -F "'" '/active_wireless/ { print }' $tmp_file` echo $signal | awk '{printf"Signal : ""\t";for(;j<;j++)printf"=";printf"\n"}' if [[ -n $signal ]] ; then echo $signal | festival --tts else echo "Not associated" | festival --tts fi done
This works by using the same process as the 'Status-->Wireless' page i.e. it gets a chunk of data by wget'ing the Status_Wireless.live.asp page from the WRT then running awk to get the relevant chunk of data (the signal strength) and then piping that into the festival speech engine.
Now I just run this script and turn up the volume on my computer when I need to move the antenna.
Small Security Script (Firewall)
#!/bin/sh # # Warning! As I don't use Emule or similiar programs I can't guaranty their function. # If you find a workable solution just add it to this wiki. # I found testing some of the setting manually that the ipfrag settings will break emule, # maybe some others too... # # Enjoy your enhanced security, # # St. Karitzl # info@user1.walztech.de # http://daywalker81.de.vu echo 1 > /proc/sys/net/ipv4/icmp_echo_ignore_all echo 1 > /proc/sys/net/ipv4/icmp_echo_ignore_broadcasts echo 1 > /proc/sys/net/ipv4/ip_forward # the following two parametes will break at least emule and are way too low to make sense. #echo 1024 > /proc/sys/net/ipv4/ipfrag_high_thresh #echo 512 > /proc/sys/net/ipv4/ipfrag_low_thresh echo 64000 > /proc/sys/net/ipv4/ipfrag_high_thresh echo 48000 > /proc/sys/net/ipv4/ipfrag_low_thresh # echo 10 > /proc/sys/net/ipv4/ipfrag_time echo 5 > /proc/sys/net/ipv4/icmp_ratelimit echo 1 > /proc/sys/net/ipv4/tcp_syncookies echo 0 > /proc/sys/net/ipv4/conf/eth1/accept_source_route echo 0 > /proc/sys/net/ipv4/conf/eth1/accept_redirects echo 1 > /proc/sys/net/ipv4/conf/eth1/log_martians echo 10 > /proc/sys/net/ipv4/neigh/eth1/locktime echo 0 > /proc/sys/net/ipv4/conf/eth1/proxy_arp echo 50 > /proc/sys/net/ipv4/neigh/eth1/gc_stale_time # # The following entries secure the last bit and provide a # moderate protection against man-in-the-middle attacks. # echo 0 > /proc/sys/net/ipv4/conf/eth1/send_redirects echo 0 > /proc/sys/net/ipv4/conf/eth1/secure_redirects echo 1 > /proc/sys/net/ipv4/icmp_ignore_bogus_error_responses echo 5 > /proc/sys/net/ipv4/igmp_max_memberships echo 2 > /proc/sys/net/ipv4/igmp_max_msf echo 1024 > /proc/sys/net/ipv4/tcp_max_orphans echo 2 > /proc/sys/net/ipv4/tcp_syn_retries echo 2 > /proc/sys/net/ipv4/tcp_synack_retries echo 1 > /proc/sys/net/ipv4/tcp_abort_on_overflow echo 10 > /proc/sys/net/ipv4/tcp_fin_timeout echo 0 > /proc/sys/net/ipv4/route/redirect_number echo 1 > /proc/sys/net/ipv4/conf/all/rp_filter echo 1 > /proc/sys/net/ipv4/conf/eth1/rp_filter echo 1 > /proc/sys/net/ipv4/tcp_syncookies echo 0 > /proc/sys/net/ipv4/conf/all/accept_source_route echo 61 > /proc/sys/net/ipv4/ip_default_ttl # DoS protection by tweaking the timeouts echo "1800" > /proc/sys/net/ipv4/tcp_keepalive_time echo "0" > /proc/sys/net/ipv4/tcp_window_scaling echo "0" > /proc/sys/net/ipv4/tcp_sack # We pretend to be a Checkpoint firewall on Windows XP echo 4096 87380 4194304 >/proc/sys/net/ipv4/tcp_rmem echo 4096 87380 4194304 >/proc/sys/net/ipv4/tcp_wmem # Check network overload (explicit congestion notification) echo 1 > /proc/sys/net/ipv4/tcp_ecn # Change port range for outgoing traffic echo "30000 60000" > /proc/sys/net/ipv4/ip_local_port_range # Change default queue size # Modified for DD-WRT because of missing proc entries echo 4096 > /proc/sys/net/ipv4/ip_conntrack_max # LED signal feedback when script ends sleep 1 gpio enable 3 sleep 1 gpio disable 3 sleep 1 gpio enable 3 sleep 1 gpio disable 2 sleep 1 gpio enable 2 sleep 1 gpio disable 2 # If you'd like to disable the web interface uncomment # the following line #killall httpd
Attention, you might have to change eth1 to the actual WAN (external) interface.
Installation is pretty simple:
- Log on to your WRT
- type
cd /jffs
- type
vi sec.sh
(or any other name) and enter the script - Connect to your WRT via web browser, page Administration:Commands
- Enter the script name (sec.sh) into the command field
- Click on "Save Startup"
- Reboot router
As a simple test try to ping your router. You should get no response otherwise you have to find the error.
Secure remote management for a WAP
Regards to the help of phusi0n dd-wrt guru and of HP from ubuntu-fr
This requires a recent >12533 to prevent milw0rm and to have the Disable "Allow any remote IP" feature. Also requires you have set the necessary port forwards in the gataways(s) on the path.
iptables -I INPUT -p tcp -j DROP iptables -I INPUT -s `nvram get lan_ipaddr`/`nvram get lan_netmask` -p tcp -m multiport --dports `nvram get sshd_port`,443 -j ACCEPT iptables -I INPUT -s `nvram get remote_ip | awk '{print }'` -p tcp -m multiport --dports `nvram get sshd_port`,443 -j ACCEPT
This allows the lowest (first) IP address set in the "Allow any remote IP" feature to connect to the https and ssh servers in the WAP (you just need the password and/or the private key) ;) . In addition, all LAN ip are allowed to do the same. Althought the "Allow any remote IP" feature doesn't work at this time when the router is set as a WAP (LAN-LAN link to the gateway, so no routing and WAN disabled, dhcp off and other stuff), this convenient script will use the first "remote_ip" you set in the GUI (wether the feature is enabled or not, as long as you stored at least one IP) and will follow the changes you could do to its static lan ip/netmask and ssh server port. Now you have full benefit of the GUI from a remote static IP and can leave the forwards enabled on the path.
--Bib 14:03, 17 May 2010 (CEST)
Block URLs with an Automatically Downloaded Host File
This was originally taken from mraneri from the Linksys forum, but was heavily modified.
#!/bin/sh logger WAN up script executing sleep 5 if test ! -s /tmp/dlhosts then cat >/tmp/dlhosts <<"EOF" #!/bin/sh logger Downloading http://www.mvps.org/winhelp2002/hosts.txt wget -O - http://www.mvps.org/winhelp2002/hosts.txt | grep 127.0.0.1 | sed '2,$s/127.0.0.1/0.0.0.0/g; s/[[:space:]]*#.*$//g;' | grep -v localhost | tr ' ' '\t' | tr -s '\t' | sort -u >/tmp/hosts0 grep addn-hosts /tmp/dnsmasq.conf || echo "addn-hosts=/tmp/hosts0" >>/tmp/dnsmasq.conf logger Restarting dnsmasq killall -1 dnsmasq EOF chmod 777 /tmp/dlhosts /tmp/dlhosts fi grep -q '/tmp/dlhosts' /tmp/crontab || echo "45 23 * * 5 root /tmp/dlhosts" >>/tmp/crontab
This script automatically downloads a host file from: "http://www.mvps.org/winhelp2002/hosts.txt" and redirects all the URLs in that file to 127.0.0.1. All those URLs are common malware or advertisement sites so is better to block them. You can also download the file, modify it with new URLs that you want to block or delete the ones you don't want to block and then upload to a web site and change the URL in the code to your custom one. Be aware that the more URLs in the file the more RAM that you will be eating from your router. Check the file size and your free memory to see if it will suit you. If not just erase some URLs... If you want to block all URLs since the router boots then just placed in the startup scripts.
Update by Aviad (A.K.A. Hotfortech): While the above works just fine, there are two main disadvantages of the above method:
1. The blocked content will be shown as "page cannot be displayed" within the websites advertisement segments and will cause the page to not load until the browser gives up on the missing object.
2. If you want to add sites to the block list, you have to do it on a per host bases... (tedious)
Enter shameless self promotion -> I have created a script on my wiki that deals with the above and more by using the pixelserv method described in the forum. you can find the script and a detailed explanation on how it works on my wiki: http://hotfortech.wikispaces.com/How+to+remove+advertisements+with+pixelserv+on+DD-WRT
Hope this helps anyone.
Directory Listing for DD-WRT Micro
Since the Micro version of DD-WRT doesn't provide a ls command, here is a very simple script to list directory contents
#!/bin/sh files=`echo *` for x in $files; do if [ -d $x ]; then echo -n "$x/ " else echo -n "$x " fi done echo
See the Telnet/SSH_and_the_Command_Line Talk page for other variants.
Global Management of Blacklists
If you have a lot of DD-WRT routers, then denying of access for abusing users through the web interface of each router can be time consuming.Here is a small firewall script to automatically download MAC-addresses of computers that should be denied access. The format of the file is Unix textfile one MAC address per line. The script assumes that you have a jffs partition. You can run it at startup by saving it as /jffs/etc/config/wifi_bl.wanup
#!/bin/sh cd /jffs rm wifi_blacklist.txt #Please modify the script to download the blacklist file from your web server wget http://www.myserver.com/wifi_blacklist.txt module_exists=`lsmod | grep ipt_mac` if [ -z "$module_exists" ] ; then insmod ipt_mac fi #Deleting the old table old_mac=`iptables -L | egrep "..:..:..:..:..:.." | sed "s/.*\(..:..:..:..:..:..\).*/\1/"` for mac in $old_mac ; do iptables -D FORWARD -p tcp -m mac --mac-source $mac -j REJECT --reject-with tcp-reset done #Adding the table again for mac in `cat /jffs/wifi_blacklist.txt` ; do iptables -I FORWARD -p tcp -m mac --mac-source $mac -j REJECT --reject-with tcp-reset done
White Listing
If you want to create a white list to block access by default but allow certain traffic through, then you can use this script to do it. Remove any junk comment lines beginning with # to save nvram space. Discuss here.
# IP Tables White Listing script by phuzi0n -Tek @ http://www.dd-wrt.com/phpBB2/viewtopic.php?t=56588 # Set up the chain iptables -N wanout iptables -I INPUT -i `nvram get lan_ifname` -j wanout iptables -I FORWARD -i `nvram get lan_ifname` -j wanout # Create whitelist 'function' script WOUT="/tmp/wanout" echo 'iptables -I wanout -j ACCEPT' > $WOUT chmod 777 $WOUT # Exempt Machine MAC # load xt_mac instead of ipt_mac on k2.6 builds insmod ipt_mac $WOUT '-m mac --mac-source 00:30:18:A9:A9:C6' # Exempt Machine IP $WOUT '-s 192.168.1.2' # Allow everyone access to these sites $WOUT '-d www.google.com' $WOUT '-d www.yahoo.com' $WOUT '-d www.dd-wrt.com' # Allow everyone access to these IP Addresses $WOUT '-d 74.125.67.100' $WOUT '-d 74.125.127.100' $WOUT '-d 74.125.45.100' $WOUT '-d 209.131.36.158' #Allow everyone access to specific destination ports $WOUT '-p udp --dport 8000' $WOUT '-p tcp --dport 80' # Everything else gets blocked iptables -A wanout -j REJECT --reject-with icmp-proto-unreachable
Reset Wireless Radio
This script solves an intermittent problem on my NetGear WNDR3300 wireless N radio. Every few hours, the wireless N radio stops broadcasting and cannot be seen by wireless clients. Bringing the wireless interface down and then back up resolves the issue. This script pings a wireless client, in my case, a WET610N wireless bridge that should always remain up and only connects to the wireless N radio. If the ping fails twice within a given time, it brings the interface down and then back up.
#!/bin/sh # This script solves an intermitent problem on my # NetGear WNDR3300 wireless N radio. Every few # hours, the wireless N radio stops broadcasting # and cannot be seen by wireless clients. Bringing # the wireless interface down and then back up # resolves the issue. This script pings a # wireless client, in my case, a WET610N wireless # bridge that should always remain up and only # connects to the wireless N radio. If the # ping fails twice within a given time, it # brings the interface down and then back up. # A wireless client that should always be up CLIENT_IP=192.168.35.250 # Wireless interface that disappears INTERFACE=`nvram get wl0_ifname` # seconds to wait after failed ping to try again FAIL_AGAIN=10 # seconds between checks CHECK_EVERY=60 # after cycling, wait this many seconds AFTER_CYCLE=360 # Client must be up before starting main loop while true do if ping -c 1 ${CLIENT_IP} >/dev/null then echo "${CLIENT_UP} ok - begining main loop" break fi done # main script while sleep ${CHECK_EVERY} do if ping -c 1 ${CLIENT_IP} >/dev/null then echo "${CLIENT_IP} ok" else echo "${CLIENT_IP} dropped one" sleep ${FAIL_AGAIN} if ! ping -c 1 ${CLIENT_IP} >/dev/null then echo "${CLIENT_IP} dropped two, sending restarting ${INTERFACE}" wl -i ${INTERFACE} down sleep 3 wl -i ${INTERFACE} up sleep ${AFTER_CYCLE} fi fi done 2>&1
Change WLAN Channel on Command Line
If you have trouble with the web interface you might find this small script useful.
It just changes the WLAN channel from the command line.
The basic idea is from here.
#!/bin/sh cur_channel=`nvram get wl_channel` usage() { cat << END Usage: `basename ` <1-14> Example: `basename ` 1 - set channel to 1 Current channel is $cur_channel END exit 1 } # Test if there is only one parameter # and if this parameter is an integer between 1 and 14 if [ $# -ne 1 ]; then usage else if echo | grep "^[0-9]*$" > /dev/null 2>&1; then if [ -gt 14 ]; then usage fi else usage fi fi echo "Setting channel from $cur_channel to " nvram set d11g_channel= nvram set wl_channel= nvram set wl0_channel= # Make the change permanent nvram commit > /dev/null 2>&1 ssid=`nvram get wl0_ssid` I=`nvram get wl0_ifname` wl -i $I channel wl -i $I ssid $ssid arp -d `nvram get lan_gateway` exit 0 # EOF
Display Connection Counts Per IP
for i in `grep 0x /proc/net/arp | cut -d ' ' -f1`; do echo "$i connection count: $(grep -c $i /proc/net/ip_conntrack)"; done
L2TP Fix for HOT users
Script for HOT users at Israel who can't connect using L2TP because DD-WRT default setting for "refuse pap=yes" while HOT setting is the opposite. Fix was risen by aviad_ra @ http://www.dd-wrt.com/phpBB2/viewtopic.php?t=17002&postdays=0&postorder=asc&highlight=l2tp&start=15
This is a cleaned up version of the same script. Add the script as a startup script.
#!/bin/sh while : ; do logger -s -p local0.notice -t L2TP "Validating \"refuse pap = no\"" while [[ -e /tmp/xl2tpd/xl2tpd.conf && -n "`cat /tmp/xl2tpd/xl2tpd.conf | grep "refuse pap = yes"`" ]] do logger -s -p local0.notice -t L2TP "Fix is needed as \"refuse pap = yes\"" cat /tmp/xl2tpd/xl2tpd.conf | sed s/"refuse pap = yes"/"refuse pap = no"/g > /tmp/xl2tpd/xl2tpd.conf.tmp mv /tmp/xl2tpd/xl2tpd.conf.tmp /tmp/xl2tpd/xl2tpd.conf logger -s -p local0.notice -t L2TP "xl2tpd.conf has been fixed" sleep 5 done sleep 30 done&
Email Bandwidth Usage Daily
This script by tc23emp will email you with the previous day's and total month's bandwidth usage. Edit it with your SMTP info. http://www.dd-wrt.com/phpBB2/viewtopic.php?p=476631#476631
#!/bin/sh aff="aff" #keyword workaround sendmail -S"smtp.comcast.net" -f"sender@comcast.net" -F"DD-WRT" -d"comcast.net" -s"Bandwidth Report" -m"$(nvram get $(date +tr$aff-%m-%Y) | awk '{print $'$(expr $(date +%d) - 1)', $NF}' | sed -e 's;\([^:]*\):\([^ ]*\) \[\([^:]*\):\([^]]*\)];Totals for Yesterday\nIncoming: \1 MB\nOutgoing: \2 MB\n\nTotals for Month to Date\nIncoming: \3 MB\nOutgoing: \4 MB\n;')" me@gmail.com > /tmp/bwmail.log 2>&1
Other Useful Misc. Scripts
These scripts will be executed through either SSH or Telnet. Once logged into you router via one of these methods, the following are quite useful:
df - Displays mounted external devices, such as USB storage. Use df -h to see the actual size values in MB
mount - Mounts an external device such as a USB HDD (Example: mount /dev/scsi/host0/bus0/target0/lun0/part1 /opt
mount --bind - Binds an old directory to a new directory (Example: mount --bind /tmp/mnt/tmp) - Type mount --help to see more options.
umount - Unmounts the external device
top - Displays all running processes including the CPU usage, Memory Usage and so on
dmesg | more - Will display Router information one segment at a time (terminal window size) and by hitting enter, the next segment is produced
netstat -an - Will display all incoming/outgoing connections
ps - Will display all running processes - Use ps --help to display more options.
free - Displays current memory statistics, and be used with extensions (Example: free -l) - Use free -? to display options
cat - Very, very useful and can display all input/output messages from the router" (Example: cat /tmp/var/log/messages) - Use cat --help for more options.
nvram show - Displays every nvram variable and available nvram space
nvram set - Set the value of an nvram variable (Example: nvram set rc_firewall="echo hello")
nvram commit - Commits nvram variables to the flash chip
reboot - Reboots the router, and must be used after an nvram commit
cd /jffs - Changes to the jffs directory
cd /mnt - Changes to the mounted directory
cd /opt - Changes to the /opt directory
These commands can also be be bound. (Example: cd /mnt/opt/etc)
NOTE: The following commands are used when the above commands have been executed
mkdir - Makes a directory, in which of course you need to specify (Example: mkdir /mnt/jffs) To mount the directory you just created, issue the following mount /mnt/jffs /jffs
rmdir - Removes the specified directory
rm - Removes a directory (Example: cd /opt then rm -rf *) -> Removes the/opt directory
killall - kill a specific process (Example: killall syslogd)
sleep - Causes the process to delay startup for specified time (Example: sleep 20 && /opt/bin/busybox swapon /dev/scsi/host0/bus0/target0/lun0/part2)
chown - Change the owner and/or group of each FILE to OWNER and/or GROUP - Type chown --help for string options
chmod - Allows permisions changing on directories (Example: chmod +x /jffs/etc/config/) - The +x string makes the directory executable.
stopservice - Stops the specified service (Example: stopservice upnp) - Replace stop with start to start the service