2017年12月27日 星期三

Extreme XOS run pyton scripts

XOS run python scripts v15.7 or high

將交換器上的 IP & MAC 往syslog 丟, 簡單將IP資料保留下



## 編緝Scripts
# vi ip2syslog.py


#!/usr/bin/python
# Client program
import sys
import io
from socket import *

f = open('/proc/self/ns_id', 'w')
f.write('2\n') #VR-DEFAUTL
f.close()

exsh.clicmd('disable clipaging', False)

# Set the socket parameters
host = "192.168.254.10"
port = 514         
buf = 1024
addr = (host,port)

# Create socket
UDPSock = socket(AF_INET,SOCK_DGRAM)
cnt = 0
for line in exsh.clicmd('show iparp', True).splitlines():
    tokens = line.split()
    if len(tokens) == 0:
        continue 
    if len(tokens) == 8:
        if tokens[2][0].isdigit():
            oui = tokens[2].lower()[:8]
            if oui:
                UDPSock.sendto('MAC:'+tokens[2]+' IP:'+tokens[1]+' port:'+tokens[-1], addr)
            cnt += 1
UDPSock.close()

## 執行scripts
# run scripts ip2syslog.py
## 收到LOG ...
    
Nov 28 03:26:56 10.100.3.145 MAC: 74:3e:cb:10:21:89 IP:192.168.1.221 port:15
Nov 28 03:26:56 10.100.3.145 MAC: 78:44:76:d6:5c:b9 IP:192.168.1.232 port:23
Nov 28 03:26:56 10.100.3.145 MAC: 74:3e:cb:10:27:4d IP:192.168.1.234 port:18
Nov 28 03:26:56 10.100.3.145 MAC: 74:3e:cb:10:22:2f IP:192.168.1.236 port:5
Nov 28 03:26:56 10.100.3.145 MAC: 74:3e:cb:10:27:49 IP:192.168.1.238 port:11
Nov 28 03:26:56 10.100.3.145 MAC: 74:3e:cb:10:27:45 IP:192.168.1.241 port:7
Nov 28 03:26:56 10.100.3.145 MAC: 00:d0:41:d8:cb:fd IP:192.168.1.242 port:23
Nov 28 03:26:56 10.100.3.145 MAC: 74:3e:cb:10:22:2b IP:192.168.1.244 port:10
Nov 28 03:26:56 10.100.3.145 MAC: 74:3e:cb:10:22:29 IP:192.168.1.245 port:12
Nov 28 03:26:56 10.100.3.145 MAC: 00:11:32:49:5e:7f IP:192.168.1.252 port:4
...
...
...
    
##在搭 upm 排程執行, 就可以簡單記錄IP & MAC


2017年8月31日 星期四

Postfix 指定特定帳號寄信到MailList


指定email 可寄到全公司帳號, 做為發送公告或通知


由scripts AD產生一個maillist

# cat /etc/postfix/maillist
#!/usr/bin/bash
echo 'all@example.com'
/usr/bin/ldapsearch -b "dc=example,dc=com" -D "example\vmail" -x -w vmail@password \
           -h 192.168.1.1  -p 389 "(&(objectClass=user)(objectCategory=person))" mail | \
           awk '{ if(match($0,/mail:/)) print " ",$2}'

產生一個檔案 virtual , 內容如:
all@example.com
    user01@example.com
    user02@example.com
    user03@example.com
    user04@example.com
不知道是不是postfix virtual 的關係, 本機 /etc/aliases不生效
原本要用 aliases 直接跑 scripts 處理掉 all:   "|/etc/postfix/maillist"


postfix 參數
check_recipient_access  :  檢查收件者email
check_sender_access : 檢查寄件者email
smtpd_restriction_classes : 增加類別, 一樣可以用, 隔開產生多個不同的類別

設定postfix main.cf
增加 virtual_alias_maps 對應到virtual
增加 smtpd_recipient_restrictions, 到第一個, 也限制permit_mynetworks
增加 smtpd_restriction_classes 一個類 trust_email

virtual_alias_maps = ldap:/etc/postfix/ad_virtual_group_maps.cf,
                                   hash:/etc/postfix/virtual 

smtpd_recipient_restrictions = check_recipient_access hash:/etc/postfix/restrict.allalias, 
                                                  permit_mynetworks,

smtpd_restriction_classes = trust_email
trust_email = check_sender_access hash:/etc/postfix/restrict.allaliasEmail, reject

限制all 只有 trust_email 才接受
cat /etc/postfix/restrict.allalias
    all@example.com trust_email

trust_email 類別內容, 指定一個或多個 email
# cat /etc/postfix/restrict.allaliasEmail
    alva@example.com OK



2017年8月28日 星期一

Rsyslog 收集所有設備SYSLOG, 依設備的IP分檔案儲存

Rsyslog增加 udp & tcp syslog 服務, RULES 來源IP分類檔案
若是有大量設備效果非常好, 也可必免單檔快速過大


cat /etc/rsyslog.conf
# Provides UDP syslog reception
$ModLoad imudp
$UDPServerRun 514
#$AllowedSender UDP, 10.0.0/8

# Provides TCP syslog reception
$ModLoad imtcp
$InputTCPServerRun 514

#### RULES ####(放在 kernel messages 前)
$template PerHostLog,"/var/log/device/%fromhost-ip%.log"
:fromhost-ip, !isequal, "127.0.0.1" ?PerHostLog
& stop


增加logrotate 以天為單位保留90天,
壓縮, 防止系統檔案被塞爆, 對文字檔案效果非常好
壓縮時預設會有日期

# vim /etc/logrotate.conf
daily
rotate 90
compress

修正syslog 目錄, 增加設備目錄檔
# vim /etc/logrotate.d/syslog 
/var/log/device/*.log


依主機設備,日期存檔, 增加日期的識別率
$template PerHostLog,"/var/log/device/%fromhost-ip%/%fromhost-ip%_%$YEAR%-%$MONTH%-%$DAY%.log"
:fromhost-ip, !isequal, "127.0.0.1" ?PerHostLog




2017年8月23日 星期三

CACTI Alert 增加 LineNotify

加入CACTI程式裡, 取代原有的2G簡訊系統, 改由LineNotify

增加在plugins: settings & thold 的function 內
# vim plugins/settings/include/functions.php
   function send_mail {}

# vim plugins/thold/thold_functions.php
   function thold_mail {}

$subject 是要傳送的文字訊息.

## line token
$ch = curl_init();
$lineurl="https://notify-api.line.me/api/notify" ;
$linehead=array("Authorization: Bearer XXXXXXXXXXXXXXXXXXXXXXXXX");
$linefields=array("message" => $subject);
curl_setopt($ch, CURLOPT_URL, $lineurl);
curl_setopt($ch, CURLOPT_HTTPHEADER, $linehead);
curl_setopt($ch, CURLOPT_NOBODY, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $linefields);
curl_exec($ch);
curl_close($ch);





另一種方式, curl 命令模式:
$ curl -X POST https://notify-api.line.me/api/notify \
          -H 'Authorization: Bearer XXXXXXXXXXXXXXXXXXXXXXXXX \
          -F 'message=alert' \
          -F 'imageFile=@/tmp/alert.jpg'


第三種, 附加圖檔(jpeg or png)
    function curl_file_create() 產生上傳檔案

<?php
if (!function_exists('curl_file_create')) {
    function curl_file_create($filename, $mimetype = '', $postname = '') {
    return "@$filename;filename="
            .($postname ?: basename($filename))
            .($mimetype ? ";type=$mimetype" : '');
    }
}

$ch = curl_init();
$lineurl="https://notify-api.line.me/api/notify" ;
$linehead=array("Content-Type: multipart/form-data",
                "Authorization: Bearer XXXXXXXXXXXXXXXXXXXXXXXXX");
$linefields = array('message' => 'Alert',
                    'imageFile' => curl_file_create('/tmp/alert.jpg'));
curl_setopt($ch, CURLOPT_URL, $lineurl);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $linehead);
curl_setopt($ch, CURLOPT_NOBODY, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $linefields);
curl_exec($ch);
curl_close($ch);
?>




2013年12月19日 星期四

刪除目錄內所有tar檔案內的特定檔案

一年排程設備備份檔案, 年初不小心在目錄內誤放了幾個不相關 img, 結果年底要燒成光碟
結果總容量共22G, 沒辨法燒錄CD, 所以只好處理*.gz檔案, 刪除img後 剩下2xxM . O_O

原本想用人工一個一個檔案處理, 結果處理到第三個就放棄, 因為有3xx多個檔案


簡單迴圈顯示目錄下所有檔案
for f in `ls`; do
  echo "File -> $f"
done
簡單迴圈顯示目錄下所有.gz檔案
for f in `ls *.gz`; do
  echo "File -> $f"
done

#看一下gz檔案內的檔案列表
tar --list --file=device.config.20131219.tar.gz


#用gunzip 將.gz 解回.tar, 刪除掉檔案, 在將檔案用 gzip 壓縮
  (zip 的檔案好像無法直接刪除檔)

for f in `ls *.gz`; do
  echo "gzip File -> $f"
  gunzip $f
  fn=`echo $f|awk -F.gz '{print $1}'`
  echo "tar File -> $fn"
  tar --delete --file=$fn tftpboot/RFS7000-5.4.4.0-007R.img
  gzip $fn
done





2013年11月8日 星期五

將整個記錄檔依指定開頭合併成為一行



將整個記錄檔依指定開頭合併成為一行
awk ' { if( $1 ~ /^Access|^Rquest|^Status/) 
            { print "\n"; printf "%s",$0 } 
            else 
            { printf "%s",$0 }
      }' analyzer.log

$1 該行的第一個字
$0 整行

依 Access 或 Request 或 Status 為開頭, 其它行接續至該末端
所以合併之後開頭只會有Access 或 Request 或 Status

print  直接印出
printf 格式化字串印出, 但會將末端換行符號刪除




常見去空白行方法
tr -s '\n' < abc.txt
grep -v "^$" abc.txt
sed '/^$/d' abc.txt
sed '/./!d' abc.txt
awk '/./' abc.txt


去除同行連續相同字
echo "abc1 abc1 abcd2 abcd3 abcd4 abcd1" |sed -e 's/\b\([a-z0-9]\+\)[ ,\n]\1/\1/g'
abc1 abcd2 abcd3 abcd4 abcd1

2013年8月5日 星期一

Fortinet Fortigate won’t save changes – CFG_CMDBAPI_ERR

 GUI出現錯誤訊息 CFG_CMDBAPI_ERR, 無法寫入或存檔 (Bug ?)

 restarts the ipsmonitor 
#diagnose test application ipsmonitor 99

檢查 forticron 的 PID, 刪除

#diag sys top 1

#diag sys kill 11 <pid>

2013年6月6日 星期四

FreeRadius Debugging Mode除錯, 自訂PHP 抓參數值

設定FreeRadius 除錯,可能依auth 或 realm 多寡不同, 連結外部OpenLDAP, MySQL等等, 而增加錯誤率, 或造成一些非遇期的動作。以下幾常見除錯方式。

1. 使用radiusd -X
開起FreeRadius Debug , 直接輸出至螢幕或至檔案。
Debug 可以看到所有流程順序, 可以各模組執行狀態, 執行在那個SECTION。

# radiusd -X
# radiusd -X > debug.txt
# radiusd -X  |  tee  debug.txt
# radiusd -X  2>&1 |  tee  debug.txt



2. 使用radsniff -X, 存看連線動作及實際回應的資訊

#radsniff -X -p 1812
-p 1812 是Radius Listen Port
可以看到連線過AVP傳輸資料,
    Access-Request
    Access-Accept
    Accounting-Request
    Accounting-Response



3. 使用tcpdump

最通用的工具, 可以查到非常細項的參數, 值, ID, Code ID,
在查RFC's, 就可以很簡單的對應Attribute list, Packet Type
匯出至檔案 由wireshark 更方便

# tcpdump udp port 1812 -vv -ttttnn

 
 


4. 使用 PHP 抓參數或值
利用FreeRadius exec 模組, 呼叫外部程式, 做一個適合自己簡單除錯程式
sites-available/default 放在設定檔的適當位置, 可以確認是否被執行到及參數是否正確
又不會一大堆不必要的訊息

增加一個模組debugtest, 捕抓使用者名稱及裝置實體位置

#vim /etc/raddb/modules/exec

exec debugtest {
wait = yes
input_pairs = request
program = "/etc/raddb/debugtest.php %{request:User-Name} %{request:Calling-Station-Id}"
shell_escape = yes
output = none

編緝一個可執行PHP SCRIPT, 捕抓帶入的Radius AVP值

# vim /etc/raddb/debugtest.php

#!/usr/bin/php
<?php
$a='' ;
for ($i=1; $i<count($argv);$i++)
{
    $a=$a.$argv[$i].' ';
}
$now=date("Y-m-d H:i:s",time());
@error_log($now." ".$a."\n", 3, "/etc/raddb/debugtest.log");
?>

編緝設定檔,

#vim sites-available/default
preacct {
             ..
             debugtest   
}

啟用Radius ,放在所需的section, 就可觀查 debugtest.log
除了不用一直盯著它, 又不會有太多不必要的資訊,

2013年4月1日 星期一

upgrade to CentOS 6.4 from CentOS 6.3/6.2/6.1/6.0

升級失敗

跳版本或升級部份套件, 有時候會有無法升級? , 可以先清除cache

# yum clean all
# yum update glibc* yum* rpm* python*
# yum update

# reboot

確認目前版本
# cat /etc/redhat-release
CentOS release 6.4 (Final)

# lsb_release -a
LSB Version:    :base-4.0-ia32:base-4.0-noarch:core-4.0-ia32:core-4.0-noarch:graphics-4.0-ia32:graphics-4.0-noarch:printing-4.0-ia32:printing-4.0-noarch
Distributor ID: CentOS
Description:    CentOS release 6.4 (Final)
Release:        6.4
Codename:       Final

加快更新速度 (限制在特定 mirror site)

安裝yum外掛套件 yum-plugin-fastestmirror
編緝         /etc/yum/pluginconf.d/fastestmirror.conf
限制在 tw範圍
include_only= .hinet.net, .twaren.net, .tw

2013年3月8日 星期五

linux 刪除超大量檔案目錄

rm on a directory with millions of files
小心使用, 注意權限 





最常用的方法, 刪除整個目錄, 用 ls 無法顯示
rm -rf (dir)

檔案數超過一定數量
find <dir> -type f -exec rm {} \;

刪除超量(用find刪不掉), 目錄大小超過數百M, 甚至數十G, 一般是主機被駭才有機會 >_<
while [ true ]; do ls -Uf | head -n 10000 | xargs rm -f 2>/dev/null; done )

export i=0;
time ( while [ true ]; do
            ls -Uf | head -n 3 | grep -qF '.png' || break;
            ls -Uf | head -n 10000 | xargs rm -f 2>/dev/null;
            export i=$(($i+10000)); echo "$i...";
       done )




命令模式, 自動化將特定網頁轉換為PDF


wkhtmltopdf  http://code.google.com/p/wkhtmltopdf/
 簡單的命令工具, 將HTML轉換為 PDF
 適合將網管上HTML報表轉出


寫個Scripts加入排程, 在固定將資料轉出來(用EMAIL也不錯), 這樣就不用每天做苦工
儲存至 /var/www/html/ntop/Report', 依月份存放至各目錄


[root@cacti ~]# cat /var/www/html/ntop/html2pdf.sh
#!/bin/bash
fileName="ntop-`date +\%Y\%m\%d-\%H`.pdf"
dirName="Report-`date +\%Y\%m`"
savePath='/var/www/html/ntop/Report'
html2pdf='/var/www/html/ntop/wkhtmltopdf-amd64'

if [ ! -d "$savePath/$dirName" ]; then
/bin/mkdir -p "$savePath/$dirName"
fi

$html2pdf "http://ntop.host.ip:3000/sortDataIP.html" "$savePath/$dirName/$fileName"




CACTI 簡單增加一個自行開發頁面, 並加入一個頁簽連結

在PHP 程式碼增加
    include("../cacti/include/global.php");

判斷session 是否存在即可
  $_SESSION["sess_user_id"]
 
安裝 Superlinks 外掛套件, 主要功能快速增加頁簽的超連結
 
 

 在Console > External Links 增加一個頁簽 Session, 連結指向你的PHP程式
 


 按Session , 測試看看
 
 
 

2012年11月5日 星期一

PHP 在APACHE 一些常用設定

不讓上傳的目錄執行PHP

httpd.conf 在網站的上傳目錄設定下
<Directory "/var/www/html/upload">
    AllowOverride None
    php_flag engine off
    Allow from all
</Directory>

.html 也能執行 PHP

# vim /etc/httpd/conf.d/php.conf

AddHandler php5-script .php .html .htm
AddType    text/html .php
AddType    application/x-httpd-php .html .htm

隱藏 Apache server information

# vim /etc/http/conf/httpd.conf
ServerSignature Off
ServerTokens Prod

隱藏 PHP version (X-Powered-By)

# vim /etc/php.ini

expose_php = Off







Prod or ProductOnly – Server sends (e.g.): Server: Apache
ServerTokens Prod

Major – Server sends (e.g.): Server: Apache/2
ServerTokens Major

Minor – Server sends (e.g.): Server: Apache/2.2
ServerTokens Minor

Min or Minimal – Server sends (e.g.): Server: Server: Apache/2.2.4
ServerTokens Min

OS – Server sends (e.g.): Server: Apache/2.2.4 (CentOS)
ServerTokens OS

Full or not specified – Server sends (e.g.): Server: Apache/2.2.4 (CentOS) PHP/5.2.3-Fedroa ServerTokens Full
ServerTokens setting applies to the entire server, and cannot be enabled or disabled on a virtualhost-by-virtualhost basis.


Web 控制 Browser Cache 的方式


 http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
 http-equiv="Pragma" content="no-cache" />
 http-equiv="Expires" content="0" />

2012年10月31日 星期三

NTOP dump data 以多種格式匯出統計資料,使用PHP計算超流量主機


 NTOP 3  “DUMP DATA”的功能可以將統計資料轉換, PHP、XML、TXT、Perl、Python格式,選擇你會用的格式,在 利用WGET排程下載檔案, 基本上也不用再做什麼加工動作,就可以拿來用每天計算,一天一個檔案,一個月目錄,當然匯入MySQL也OK。

#wget -O ntop-20121031-2350.php "http://127.0.0.1:3000/dumpData.html?language=php&view=short"


$ntopHash = array(
'192.168.1.1' => array(
        'hostSymIpAddress' => 'xxx.ntop.org',
        'pktSent' => '1031',
        'pktRcvd' => '922',
  ...
        'icmpRcvd' => '0',
),
...

由NTOP頁面手動下載:

檔案內容:


PHP 計算總流量超過4G的主機列表





<?php
date_default_timezone_set("Asia/Taipei");

$max=4096000000;
$ntopLogPath="/samba/Report/phpntop";
$filelist=read_dir($ntopLogPath);
rsort($filelist);

if (isset($_GET['list']))
{ $logfile=$_GET['list']; }
else
{ $logfile=$filelist[0]; }
if (file_exists( $ntopLogPath."/".$logfile))
{ include $ntopLogPath."/".$logfile; }
else
{ $ntopHash=''; }

echo "<script src='sorttable.js'></script>" ;
echo "<style type='text/css'>\n";
echo "<!-- \n";
echo "a { \n";
echo " text-decoration: none; \n";
echo "} \n";
echo "--> \n";
echo "</style> \n";

echo "<TABLE>\n ";
echo " <TR>\n";
echo " <TD VALIGN='TOP'>\n";
echo "<TABLE>\n ";
echo " <TR><TD>File List</TD></TR>";
for ($i=0; $i<count($filelist); $i++)
{
echo " <TR onMouseOver=\"this.bgColor = '#F9B7FF'\" onMouseOut =\"this.bgColor = '#FFFFFF'\">\n";
echo "<TD><A HREF='ntop.php?list=".$filelist[$i]."'>
<FONT COLOR='#0000FF'>".substr($filelist[$i],0,-4)."</FONT></A></TD></TR>\n";
}
echo "</TABLE>\n ";
echo " </TD>\n";


echo " <TD VALIGN='TOP'>\n";

$ip=@array_keys($ntopHash);
#http://ntop.example.com/report/Report-201202/ntop-daily/
#$downLoadPath="http://ntop.example.com/report/Report-".date("Ym",time())."/ntop-daily/";
$downLoadPath="http://ntop.example.com/report/Report-".substr($logfile,5,6)."/ntop-daily/";
echo "Date : ".substr($logfile,0,-4);
echo "<A HREF='$downLoadPath'><FONT COLOR='#0000FF'> DownLoad File</FONT></A><BR />\n";
#echo "Total IP:".count($ip);
echo "<HR />\n";
echo "Traffic >4G :";
echo "<TABLE border='1' style='border-collapse:collapse;' borderColor='black' class='sortable'>\n";
echo " <TR>\n";
echo " <TD>IP</TD>\n";
echo " <TD>Total</TD>\n";
echo " <TD>Send</TD>\n";
echo " <TD>Rcvd</TD>\n";
echo " <TD>tcpBytesSent</TD>\n";
echo " <TD>tcpBytesRcvd</TD>\n";
echo " <TD>udpBytesSent</TD>\n";
echo " <TD>udpBytesRcvd</TD>\n";
echo " </TR>\n";

for ($i=0; $i<(count($ip)); $i++)
{
$key=$ip[$i];
$total=$ntopHash[$key]['bytesSent']+$ntopHash[$key]['bytesRcvd'];
if ($total>$max)
{
echo " <TR onMouseOver=\"this.bgColor = '#3BB9FF'\" onMouseOut =\"this.bgColor = '#FFFFFF'\">\n";
echo " <TD>".$ntopHash[$key]['hostResolvedName']."</TD>\n ";
echo " <TD align='right'>".formatBytes($total)."</TD>\n";
echo " <TD align='right'>".formatBytes($ntopHash[$key]['bytesSent'])."</TD>\n";
echo " <TD align='right'>".formatBytes($ntopHash[$key]['bytesRcvd'])."</TD>\n";
echo " <TD align='right'>".formatBytes($ntopHash[$key]['tcpBytesSent'])."</TD>\n";
echo " <TD align='right'>".formatBytes($ntopHash[$key]['tcpBytesRcvd'])."</TD>\n";
echo " <TD align='right'>".formatBytes($ntopHash[$key]['udpBytesSent'])."</TD>\n";
echo " <TD align='right'>".formatBytes($ntopHash[$key]['udpBytesRcvd'])."</TD>\n";
echo " </TR>\n";
}
}
echo "</TABLE>\n";

echo " </TD>\n";
echo " </TR>\n";
echo "</TABLE>\n";
###########################################################
function formatBytes($size, $precision = 2)
{
if ($size==null)
return "0";
$base = log($size) / log(1024);
$suffixes = array('', 'k', 'M', 'G', 'T');

return round(pow(1024, $base - floor($base)), $precision) . $suffixes[floor($base)];
}
function read_dir($dir, $array = array())
{
$dh = opendir($dir);
$files = array();
while (($file = readdir($dh)) !== false) {
$flag = false;
if($file !== '.' && $file !== '..' && !in_array($file, $array)) {
$files[] = $file;
}
}
return $files;
}
?>

2012年8月29日 星期三

PHP-EXPECT SSH應用(TELNET)

使用expect可以簡單達到自動交互作用,之前都在SHELL底下工作,用排程完成相關作業。
最近使用PHP expect 移到WEB介面,可遠端利用WEB更輕鬆完成操作,搭配PHP語法更容控制整個程序,不用考慮SHELL下的權限問題。

底下範例:

使用TELNET連至EXTREME交換設備進行命作操作,針對抓取線上使用者MAC,收集所有MAC,針對異常MAC限制存取。


<?php
function getExtreme($cmd,$ip,$arg='')
{
switch ($cmd)
    {
    case "fdb":
        #取得MAC位置
        $cmdString="show fdb \n \n" ;
        break;
    case "setdenymac":
        #設定ACL
        $aclName="deny-$arg";
        $mac=preg_replace('/-/', ':',$arg);
        $cmdString=" create access-list $aclName \"ethernet-source-address $mac\" \"deny\" \n
        configure access-list add \"$aclName\" first any \n ";
        break;
    case "deldenymac":
        #刪除ACL
        $aclName="deny-$arg";
        $mac=preg_replace('/-/', ':',$arg);
        $cmdString="configure access-list delete \"$aclName\" any \n
        delete access-list \"$aclName\" \n ";
        break;
    default:
        return null;
    }
ini_set("expect.timeout", 3);
ini_set("expect.loguser", "Off");
##訂定常數
@define("LOGIN", 'login:');
@define("PASSWORD", 'password:');
@define("SHELL", '#');
@define("YESNO",'(y/N)');
#EXP_EXACT ..
## login get data
$stream = fopen("expect://telnet $ip", "r");
#$stream = expect_popen("telnet $ip");
$status=1;
while ($status) {
    switch (expect_expectl ($stream, array (
    array ('login:', 1 => LOGIN),
    array ('password:', 1 => PASSWORD),
    array ('#', 1 => SHELL, EXP_EXACT),
    array ('(y/N)', 1 => YESNO)
    ),$result))
    {
        case @LOGIN:
            fwrite ($stream, "cmdadmin\n");
            #echo "login\n" ;
        break;
            case @PASSWORD:
            fwrite ($stream, "cmdadminpw\n");
            #echo "password\n" ;
        break;
            case @SHELL:
            #echo 'shell';
            fwrite ($stream, $cmdString);
            sleep(1);
            fwrite ($stream, "exit\ny\n");
        break 2;
            case @YESNO:
            fwrite ($stream, "y\n");
            #echo "YESNO\n" ;
            break;
            case @EXP_TIMEOUT:
            case @EXP_EOF:
            $status=0;
        break 2;
            default:
            die ("Error has occurred!\n");
        break;
    }
}
## get output messages
$line = stream_get_contents($stream) ;
fclose ($stream);
switch ($cmd)
{
    case "fdb" :
    ## next page
    $tag="/ \[7mPress <SPACE> to continue or <Q> to quit: \[m \[60;D \[K/";
    $line = preg_replace($tag, '', $line);
    # ascii 0d 0a
    $log = explode("\r\n",$line);
    $fdblist = '';
    $pattern = "/([a-f0-9]{2}:){5}[a-f0-9]{2}/";
    for ($i=0; $i<count($log); $i++)
    {
        if (preg_match($pattern,$log[$i]))
        {
            #replace muitl space
            $log[$i]=preg_replace('/\s\s+/', ' ',$log[$i]);
            $fdblist[$i]=explode(' ',$log[$i]);
        }
    }
    return $fdblist;
    break;
    default:
    return true;
}
}
?>

#抓取有IP 192.168.200.253線上MAC(將Switch列在清單,就能一次取得線上所有主機MAC
使用方法:
print_r(getExtreme('fdb', '192.168.200.253')

 



#設定MAC ACL (該MAC就會無法存取)
getExtreme('setdenymac', '192.168.200.253','00:01:e6:b0:e2:a9')

#刪除MAC ACL (解除MAC ACL)
getExtreme('deldenymac', '192.168.200.253','00:01:e6:b0:e2:a9')

應用在WEB,已點選方式快速建立黑白名單,再與L3結合將IP及MAC關連

圖:線上管理

2012年8月7日 星期二

Fortigate disable IPS engines

Version: Fortigate-3240C v4.0,build4188,120620 (MR3)

FG3240C-HA# diag test application ipsmonitor 98
FG3240C-HA# diagnose sys top
Run Time:  1 days, 8 hours and 49 minutes
0U, 0S, 100I; 10956T, 6128F, 193KF
     proxyworker       80      S       0.0     0.9
          cw_acd      116      S       0.0     0.4
         cmdbsvr       57      S       0.0     0.4
          httpsd      168      S       0.0     0.3
          httpsd      122      S       0.0     0.3
       forticron       77      S       0.0     0.2
          httpsd       70      S       0.0     0.2
         miglogd       68      S       0.0     0.2
       scanunitd      130      S <     0.0     0.1
       scanunitd      124      S <     0.0     0.1
       scanunitd      128      S <     0.0     0.1
       scanunitd      129      S <     0.0     0.1
       scanunitd      125      S <     0.0     0.1
       scanunitd      126      S <     0.0     0.1
       scanunitd      127      S <     0.0     0.1
       scanunitd      123      S <     0.0     0.1
       scanunitd       73      S <     0.0     0.1
       urlfilter       79      S       0.0     0.1
       wad_diskd       72      S       0.0     0.1
          newcli     1525      R       0.0     0.1



# diag test application ipsmonitor IPS Engine Test Usage: (Values for >
1: Display IPS engine information
2: Toggle IPS engine enable/disable status
3: Display restart log
4: Clear restart log
5: Toggle bypass status
6: Submit attack characteristics now
97: Start all IPS engines
98: Stop all IPS engines
99: Restart all IPS engines and monitor


The most common command that we issue to deal with the IPS Engine running high is the following which restarts the IPS process:

# diag test application ipsmonitor 99

config ids process (default 8)
#config system global
    set proxy-worker-count 1
end

# diagnose debug crashlog clear
# diagnose debug crashlog get


2012年8月1日 星期三

PHP 查詢已載入模組, 查詢模組功能

##檢查'rrdtool'是否載入, 若不存在就動態載入

<?php
  if (!extension_loaded('rrdtool'))
  {
     if (function_exists('rrdtool')
     {
       dl('rrdtool.so');
     }
  }
  dl('gd.so');
 #列出所有已載入的模組
  print_r(get_loaded_extensions());
  echo "xml modules\n";
  #列出模組XML, 的所有FUNC
  print_r(get_extension_funcs("xml"));

?>


Array
(
    [0] => Core
    [1] => date
    [2] => ereg
    [3] => libxml
...
)
Array
(
    [0] => xml_parser_create
    [1] => xml_parser_create_ns
    [2] => xml_set_object
...
)


#列出所有已載入的模組
phpinfo(INFO_MODULES);


##命令 查詢已載模組
# php -m

php.ini , 是否允許動態載入模組
  enable_dl = Off

預設模組載入路徑 /etc/php.d/
# more /etc/php.d/ssh2.ini
   extension=ssh2.so

# ls /usr/lib64/php/modules/
curl.so    fileinfo.so  json.so    mysql.so      pdo.so         phar.so     snmp.so     ssh2.so
expect.so  gd.so        mysqli.so  pdo_mysql.so  pdo_sqlite.so  rrdtool.so  sqlite3.so  zip.so



CentOS6 x86_64

2012年7月20日 星期五

VMware-Workstation 建立 RHEV-H 3.0 LAB環境

Configuring KVM / RHEV-H 3.0 VM inside VMware workstation
RHEV-H 建立,


建立自訂VM完成後, 需要在編緝 RHEVH.vmx , 確認是否正確,可能會造成無法安裝。
造成:開機就會當機及出現Kernel panic - not syncing: Attempted to kill init! (hdd 不支援, 沒驅動)
  •  CPU支援VT
  •  電源管理
               apic.xapic.enable = FALSE
  •  硬碟
               scsi0.virtualDev = "lsisas1068" 

1.

2.

3.
4.
5.
6.
7.
8.
LSI logic SAS (RHEVH 支援的硬碟)
9.
10.
11.
12.
13.
14.
15.
16. 
編緝vmx檔, 關閉電源管理
apic.xapic.enable = FALSE





一般最少建立兩台RHEV-H, 才能完全測到全部的功能, 玩起來比較有感覺。












2012年5月27日 星期日

PHP-EXPECT SSH應用(TELNET)

使用expect可以簡單達到自動交互作用,之前都在SHELL底下工作,用排程完成相關作業。
最近使用PHP expect 移到WEB介面,可遠端利用WEB更輕鬆完成操作,搭配PHP語法更容控制整個程序,不用考慮SHELL下的權限問題。

底下範例:

使用SSH連至設備進行命作操作,針對MOTOROLA RFS 抓取線上無線使用者IP

<?php
ini_set("expect.timeout", 10);
ini_set("expect.loguser", "Off");
define("PASSWORD", 'password:');
define("YESNO", 'yes/no)?');  ##first once for ssh key
define("ENABLEMODE", '*>');
define("SHELL", '*#');
#EXP_EXACT ..
$stream = fopen("expect://ssh sshcmd@10.209.8.1", "r");
#$stream = expect_popen("ssh sshcmd@10.209.8.1");
$status=1;
while ($status) {
    switch (expect_expectl ($stream, array (
            array ('password:', 1 => PASSWORD),
            array ('yes/no)?', 1 => YESNO),
            array ('*>', 1 => ENABLEMODE),
            array ('*#', 1 => SHELL, EXP_EXACT)
           ),$result))
     {
        case @PASSWORD:
            fwrite ($stream, "password\n");
            break;
        case @YESNO:
            fwrite ($stream, "yes\n");
            break;
        case @ENABLEMODE:
            fwrite ($stream, "enable\n");
            break;
        case @SHELL:
            fwrite ($stream, "show wireless client \n        " );
            sleep(3);  ##wait output
            fwrite ($stream, "exit \n");
            break 2;
        case @EXP_TIMEOUT:
        case @EXP_EOF:
            $status=0;
            break 2;
        default:
            die ("Error has occurred!\n");
    }
}
## show messages
    $line = stream_get_contents($stream) ;
    fclose ($stream);
    print_r($line);
?>

部份PHP 就沒有貼上來,僅貼連結MoTo RFS7000控制部份。
主要PHP程式是控制,線上增加及刪除使用者裝置MAC,使用者自行登入註冊MAC,來MAC存取控管,原本要從RFS7000設備上手動命令設定,現在只要WEB介面讓使用者點點按鈕就可了。
 
 

@SHELL  顯示如果有多頁顯示時需要按任一鍵繼續換頁(強迫性),所以 \n 後面接幾個控白字元來換頁,同時也可能需要等待結果的輸出,在加上seleep(3),若未等待可能造成下一個指令無法正確執行。
在linux 上系統就比較不會發生這種問題,大都是一個命令就全部顯示,不需換行的動作。

@YESNO  是控制SSH第一次接收public key動作。



在 CentOS6 需要安裝pecl, 同時也要安裝 ssh2 , expect, 才能正常執行PHP_EXPECT
# pecl list
Installed packages, channel pecl.php.net:
=========================================
Package  Version State
expect   0.3.1   beta
ssh2     0.11.2  beta

安裝php ssh2 & expect 模組

作業環境 : CentOS6-64bit

1. pear & pecl 是PHP用來擴充套件( extensions )的程式,pecl 在php-pear套件內

# yum install php-pear
# pecl list-all
安裝 ssh2 & expect ,因為兩個模組都是beta套件,所以無法直接安裝,會有提示bete安裝方式
# pecl install ssh2
# pecl install expect

# pecl install channel://pecl.php.net/ssh2-0.11.3
# pecl install "channel://pecl.php.net/expect-0.3.1"
#安裝完成,檢視已安裝的模組
# pecl list
Installed packages, channel pecl.php.net:
=========================================
Package Version State
expect 0.3.1 beta
ssh2 0.11.3 beta

#確認模組是否正確編譯成功(.so)
# ls /usr/lib64/php/modules/

預設不會掛載pecl 編譯出來的PHP 模組, 必須手動設定
# vim /etc/php.d/ssh2.ini
   extension=ssh2.so
# vim /etc/php.d/expect.ini
   extension=expect.so

#service httpd restart

設定完成


2. 安裝過程中可能發生錯誤(相依套件)

# pecl install channel://pecl.php.net/ssh2-0.11.3
WARNING: channel "pecl.php.net" has updated its protocols, use "pecl channel-update pecl.php.net" to update
downloading ssh2-0.11.3.tgz ...
Starting to download ssh2-0.11.3.tgz (23,062 bytes)
.....done: 23,062 bytes
5 source files, building
running: phpize

sh: phpize: command not found
ERROR: `phpize' failed

缺少PHP 可執行腳本 編譯軟體,但看一下就知道前面安裝的套件,就知道可能需要那些套件。

# yum install php-devel.x86_64  
# yum install libssh2-devel.x86_64
# yum insatll expect-devel.x86_64
# yum insatll tcl-devel.x86_64

phpize 是屬於 php-devel 中的東西,主要是設定 php 外掛模塊的一些設定
php安裝成功後,在bin目錄下會生成一個phpize的可執行腳本,它的用途是用來動態安裝php擴充模組。使用phpize的好處是:在已經安裝了php的情況下,再安裝擴展模塊時,無需重新編譯安裝php。

Extreme XOS run pyton scripts

XOS run python scripts v15.7 or high 將交換器上的 IP & MAC 往syslog 丟, 簡單將IP資料保留下 ## 編緝Scripts # vi ip2syslog.py #!/usr/bin/python # ...