====== Полезные скрипты для mikrotik ======
==== Бекап конфигов микрота и отправляем на удаленный FTP сервер ====
{
local username "никнейм"
#ftp account
local ftphost "имя сервера"
local ftpuser "логин"
local ftppassword "пароль"
local ftppath "/pub/mikrotik"
#create full system backup files
/system backup save name="$username.backup"
:delay 30s;
#create config export files
/export compact file="$username.rsc"
:delay 30s;
# upload the system backup
:log info message="Uploading system backup"
/tool fetch address="$ftphost" src-path="$username.backup" user="$ftpuser" mode=ftp password="$ftppassword" dst-path="$ftppath/$username.backup" upload=yes
:delay 30s;
# upload the config export
:log info message="Uploading config export"
/tool fetch address="$ftphost" src-path="$username.rsc" user="$ftpuser" mode=ftp password="$ftppassword" dst-path="$ftppath/$username.rsc" upload=yes
:delay 30s;
# find file name $username- then remove
:foreach i in=[/file find] do={ :if ([:typeof [:find [/file get $i name] "$username"]]!="nil") do={/file remove $i}; }
:log info message="Configuration backup finished.";
}
==== Бекап по частям ====
Микротик1 (экспорт):
ip firewall export file=ip-firewall.rsc
ip pool export file=ip-pool.rsc
ip route export file=ip-route.rsc
Микротик2 (импорт):
import file=ip-firewall.rsc
import file=ip-pool.rsc
import file=ip-route.rsc
==== Добавляем автоматически 254 маршрута ====
for x from=1 to=254 do={ /ip route add dst-address="192.168.$x.0/24" gateway=192.168.201.10 }
==== Указываем мост одной командой для всех интерфейсов ====
>interface bridge port add interface=ether1 bridge=bridge-local; ip address set 0 interface=bridge-local; ip dhcp-server set 0 interface=bridge-local
==== Меняем MAC на интерфейсе на свой ====
/interface ethernet set ether1 mac-address=00:01:00:00:00:00
==== Проверяем шлюз провайдера, если он отличается от статического — синхронизируем ====
:global ispgw [ip dhcp-client get [/ip dhcp-client find interface=ether1-gateway] gateway ];
:global ispgwstat [ip route get [/ip route find comment="ISP1" ] gateway ];
#:log info ("$ispgw" )
#:log info ("$ispgwstat" )
:if ($ispgw = $ispgwstat ) do={ :log info ("ISP GW OK" ) } else={ ip route set [/ip route find comment="ISP1"] gateway=$ispgw; :log info ("ISP GW COMPLETE" )}
==== Если через PPPOE соединение некоторые сайты не открываются ====
Необходимо сделать изменения в Firewall > Mangle.
Удалить динамические правила change MSS all ppp.
Добавить правило:
/ip firewall mangle add action=change-mss chain=forward new-mss=1360 protocol=tcp tcp-flags=syn tcp-mss=1453-65535
Изменить профиль, что бы динамические правила больше не создавались:
PPP > Prifiles > Default > General > Change TCP MSS “no”
==== Локальное перенаправление портов ====
/ip firewall nat
add action=dst-nat chain=dstnat dst-address=192.168.224.1 dst-port=8181 \
in-interface=bridge-local protocol=tcp src-address=192.168.224.0/24 \
to-addresses=192.168.224.20 to-ports=8080
add action=dst-nat chain=dstnat dst-address=192.168.224.1 dst-port=8182 \
in-interface=bridge-local protocol=tcp src-address=192.168.224.0/24 \
to-addresses=192.168.224.20 to-ports=555
add action=src-nat chain=srcnat dst-address=192.168.224.20 dst-port=8080 \
out-interface=bridge-local protocol=tcp src-address=192.168.224.0/24 \
to-addresses=192.168.224.1 to-ports=8181
add action=src-nat chain=srcnat dst-address=192.168.224.20 dst-port=555 \
out-interface=bridge-local protocol=tcp src-address=192.168.224.0/24 \
to-addresses=192.168.224.1 to-ports=8182
==== Прикручиваем клиент DDNS сервиса no-ip.org #2 ====
##############Script Settings##################
:local NOIPUser "логин_ноип"
:local NOIPPass "пароль_ноип"
:local WANInter "интерфейс_в_инет"
###############################################
:local NOIPDomain "домен_ноип"
:local IpCurrent [/ip address get [find interface=$WANInter] address];
:for i from=( [:len $IpCurrent] - 1) to=0 do={
:if ( [:pick $IpCurrent $i] = "/") do={
:local NewIP [:pick $IpCurrent 0 $i];
:if ([:resolve $NOIPDomain] != $NewIP) do={
/tool fetch mode=http user=$NOIPUser password=$NOIPPass url="http://dynupdate.no-ip.com/nic/updateFhostname=$NOIPDomain&myip=$NewIP" keep-result=no
:log info "NO-IP Update: $NOIPDomain - $NewIP"
}
}
}
==== Дописать текст в файл ====
:local ts [/system clock get time]
:set ts ([:pick $ts 0 2].[:pick $ts 3 5].[:pick $ts 6 8])
:local ds [/system clock get date]
:set ds ([:pick $ds 7 11].[:pick $ds 0 3].[:pick $ds 4 6])
:local ContentsFile [/file get isp-stat.txt contents];
/file set isp-stat.txt contents="$ContentsFile\nISP DOWN-$ds-$ts"
==== Проверка средней скорости интернет и запись в log файл ====
:local txAvg 0
:local rxAvg 0
:local ts [/system clock get time]
:set ts ([:pick $ts 0 2].[:pick $ts 3 5].[:pick $ts 6 8])
:local ds [/system clock get date]
:set ds ([:pick $ds 7 11].[:pick $ds 0 3].[:pick $ds 4 6])
tool bandwidth-test protocol=tcp direction=transmit address=ip_bandsw_test_server duration=5s do={
:set txAvg ($"tx-total-average" / 1048576 );
}
tool bandwidth-test protocol=tcp direction=receive address=ip_bandsw_test_server duration=5s do={
:set rxAvg ($"rx-total-average" / 1048576 );
}
:local ContentsFile [/file get isp-quality.txt contents];
/file set isp-quality.txt contents="$ContentsFile\n$ds-$ts tx: $txAvg Mbps - rx: $rxAvg Mbps"
==== Цвет лога ====
log info "blah blah this log is in black"
log warning "blah blah this log is in blue"
log error "blah blah this log is in red"
==== Проверка баланса, оператор Life (автор AHouse) ====
/tool sms set receive-enabled=yes
/tool sms inbox remove [/tool sms inbox find phone="5433"]
/log info "Get current ballance"
/tool sms send usb5 phone-number=5016 message="CHECKBALANCE"
#ждем смску сбаллансом
/log info "Delay 60s..."
:delay 60s
/log info "Searching Ballance message..."
:local SMSGateBallance [ :pick [/tool sms inbox get value-name=message number=[/tool sms inbox find phone="5433"]] 0 15 ]
#/log info $SMSGateBallance
:if ([:len $SMSGateBallance] >1) do={ /log info $SMSGateBallance } else={ /log info "Ballance SMS not found !!!" }
==== Скрипт проверяет смену IP домена DDNS и меняет IP в поле «Host:» NetWatch ====
:global dnshostname "alik.no-ip.org"
:global currentip [:resolve $dnshostname]
:log info "Current loopback ip alik: ($currentip)"
:global oldip [/tool netwatch get [/tool netwatch find comment="alik"] host]
:log info "Old loopback ip alik: ($oldip)"
:if ($currentip = $oldip ) do={ :log info ("Alik NW OK" ) } else={ /tool netwatch set [/tool netwatch find comment="alik"] host=$currentip; :log info ("Alik NW COMPLETE" )}
==== Сброс повисших сессий на порту 5060 ====
:foreach i in=[/ip firewall connection find dst-address~":5060" protocol~"udp"] do={ /ip firewall connection remove $i }
или
:local pingcount 5;
:local hostping 8.8.8.8;
:local pingresultA [/ping $hostping count=$pingcount];
:if ($pingresultA > 0) do={:put "connect"} else= { :foreach i in=[/ip firewall connection find dst-address~":5060" protocol~"udp"] do={ /ip firewall connection remove $i } }
==== Реконект активного соединения ppp ====
/ppp active remove numbers=[/ppp active find where name="ppp-name-connect"]]
==== Пересылка SMS на E-Mail ====
# Скрипт проверяет наличие входящих SMS
# и по-sms-но отправляет их на e-mail
# Должен быть настроен email-клиент на микротике
# DEBUGMODE "True" - будет отладка в лог.
:local DEBUGMODE "False"
# EMail адрес получателя
:local DSTEMail "ahousе@mаil.ru"
:if ( $DEBUGMODE="True" ) do={/log info "sms 2 email DEBUG ...";}
/tool sms set receive-enabled=yes
:delay 30s
:local SMSMSG ""
:local SMSPHONE ""
:local SMSDate ""
:local InboxSMSCount [/tool sms inbox print count-only]
:if ( $DEBUGMODE="True" ) do={/log info "INBOX SMS Count: $InboxSMSCount";}
:if ($InboxSMSCount >0) do={
:local InBoxSMSArray [:toarray [/tool sms inbox find]]
:foreach CurrentSMS in=$InBoxSMSArray do={
:if ( $DEBUGMODE="True" ) do={/log info "SMS ID# $CurrentSMS";}
:set SMSPHONE [ /tool sms inbox get value-name=phone number=$CurrentSMS ];
:set SMSDate [ /tool sms inbox get value-name=timestamp number=$CurrentSMS ];
:set SMSMSG [ /tool sms inbox get value-name=message number=$CurrentSMS ];
:if ( $DEBUGMODE="True" ) do={/log info $SMSPHONE;}
:if ( $DEBUGMODE="True" ) do={/log info $SMSDate;}
:if ( $DEBUGMODE="True" ) do={/log info $SMSMSG;}
:if ( [:len $SMSMSG] >0 ) do={
:if ( $DEBUGMODE="True" ) do={/log info "Sending SMS 2 EMail $DSTEMail ....";}
/tool e-mail send from=rb@ahosting.net.ua to=$DSTEMail body="PHONE: $SMSPHONE\nDATE: $SMSDate\nMSG: $SMSMSG" subject="AR SMS-Gateway INBOX SMS#$CurrentSMS"
}
:if ( $DEBUGMODE="True" ) do={/log info "Clearing INBOX SMS# $CurrentSMS";}
/tool sms inbox remove numbers=$CurrentSMS
}
} else {:if ( $DEBUGMODE="True" ) do={/log info "INBOX empty";} }
:if ( $DEBUGMODE="True" ) do={/log info "Sending SMS 2 EMail COMPLITED!!!";}
==== Баланс на сим карте ====
/tool sms set receive-enabled=yes
/tool sms inbox remove [/tool sms inbox find phone="5433"]
/log info "Get current ballance"
/tool sms send usb5 phone-number=5016 message="CHECKBALANCE"
#ждем смску сбаллансом
/log info "Delay 60s..."
:delay 60s
/log info "Searching Ballance message..."
:local SMSGateBallance [ :pick [/tool sms inbox get value-name=message number=[/tool sms inbox find phone="5433"]] 0 15 ]
#/log info $SMSGateBallance
:if ([:len $SMSGateBallance] >1) do={ /log info $SMSGateBallance } else={ /log info "Ballance SMS not found !!!" }