runlink(linkfile){ FileGetShortcut, % linkfile, OutTarget, OutDir, OutArgs SetWorkingDir % OutDir Run, % """" OutTarget """" (OutArgs ? " """ OutArgs """" : "") SetWorkingDir % A_ScriptDir }
;duplicate top10 src = ( 加 就 加 加 加 的 到 否 的 额 一 他 个 飞 的 的 他 的 对 额 额 他 哦 平 去 我 额 人 啊 是 的 飞 个 好 ) a := [] b = loop, Parse, src, `n, `r { if !a["" A_LoopField] a["" A_LoopField] := 1 else a["" A_LoopField] += 1 } for c,d in a { d2 := SubStr("00000", 1, 5-strlen(d)) d str := d2 "_" c b .= b ? "`n" str : str } Sort, b, R e := StrSplit(b,"`n","`r") f = loop 10 f .= f ? "`n" e[A_index] : e[A_index] MsgBox % f
MD5 16位是32位截取的
SubStr(md5,9,16)
HashFromAddr(pData, len, algid, key=0) { hProv := size := hHash := hash := "" ptr := (A_PtrSize) ? "ptr" : "uint" aw := (A_IsUnicode) ? "W" : "A" if (DllCall("advapi32\CryptAcquireContext" aw, ptr "*", hProv, ptr, 0, ptr, 0, "uint", 1, "uint", 0xF0000000)) { if (DllCall("advapi32\CryptCreateHash", ptr, hProv, "uint", algid, "uint", key, "uint", 0, ptr "*", hHash)) { if (DllCall("advapi32\CryptHashData", ptr, hHash, ptr, pData, "uint", len, "uint", 0)) { if (DllCall("advapi32\CryptGetHashParam", ptr, hHash, "uint", 2, ptr, 0, "uint*", size, "uint", 0)) { VarSetCapacity(bhash, size, 0) DllCall("advapi32\CryptGetHashParam", ptr, hHash, "uint", 2, ptr, &bhash, "uint*", size, "uint", 0) } } DllCall("advapi32\CryptDestroyHash", ptr, hHash) } DllCall("advapi32\CryptReleaseContext", ptr, hProv, "uint", 0) } int := A_FormatInteger SetFormat, Integer, h Loop, % size { v := substr(NumGet(bhash, A_Index-1, "uchar") "", 3) while (strlen(v)<2) v := "0" v hash .= v } SetFormat, Integer, % int return hash } HashFromString(string, algid, key=0) { len := strlen(string) if (A_IsUnicode) { ;VarSetCapacity(data, len) ;StrPut(string, &data, len, "cp0") return HashFromAddr(&data, len, algid, key) } data := string return HashFromAddr(&data, len, algid, key) } MD5(string,b16:=false) { ;0x8003/*_CALG_MD5*/ ;0x8001/*_CALG_MD2*/ ;0x8002/*_CALG_MD4*/ ;0x8004/*_CALG_SHA1*/ return b16 ? SubStr(HashFromString(string, 0x8003),9,16) : HashFromString(string, 0x8003) } MsgBox % md5(Ansi2UTF8("我们"),1)
/* ;示例 dd := new DD() ;鼠标绝对移动 dd.mov(500,500) ;按键 dd.key(401) ;输入文字 str = Autohotkey loop % strlen(str) dd.str(SubStr(str,A_index,1)) */ class DD { __New() { ;加载DD 32位 dll 请重命名成DD.dll放到脚本目录 IfNotExist, DD.dll { RegRead, dd_path, HKLM, SOFTWARE\DD XOFT, path if !dd_path { MsgBox, 4112, 错误, DD.dll未找到! return } else { this.hModule := DllCall("LoadLibrary", "Str", dd_path, "Ptr") } } else { this.hModule := DllCall("LoadLibrary", "Str", "DD.dll", "Ptr") } } __Delete() { DllCall("FreeLibrary", "Ptr", this.hModule) } btn(btn) ;鼠标按键 { return DllCall("DD\DD_btn","Int",btn) } mov(x,y) ;鼠标绝对移动 { return DllCall("DD\DD_mov","Int",x,"Int",y) } movR(dx,dy) ;鼠标相对移动 { return DllCall("DD\DD_movR","Int",dx,"Int",dy) } key(key,flag) ;键盘按键 key:DD专用虚拟键码 flag:按下=1,放开=2 { return DllCall("DD\DD_key","Int",key,"Int",flag) } whl(flag) ;鼠标滚轮 按下=1,放开=2 { return DllCall("DD\DD_whl","Int",flag) } str(str) ;直接输入键盘上的可见字符 { return DllCall("DD\DD_str","Ptr",&str) } todc(vkcode) ;虚拟键码转DD键码 { return DllCall("DD\DD_todc","Int",vkcode) } MouseMove(hwnd,x,y) ;窗口内鼠标移动 hwnd:窗口句柄,为0时表示全屏,等同mov { return DllCall("DD\DD_MouseMove","Int",hwnd,"Int",x,"Int",y) } SnapPic(hwnd,x,y,w,h) ;抓图 hwnd:窗口句柄,为0时表示全屏 暂时无法使用 { return DllCall("DD\DD_SnapPic","Int",hwnd,"Int",x,"Int",y,"Int",w,"Int",h) } PickColor(hwnd,x,y,const:=0) ;窗口内取色 hwnd:窗口句柄,为0时表示全屏 const:常量始终等于0 暂时无法使用 { return DllCall("DD\DD_PickColor","Int",hwnd,"Int",x,"Int",y,"Int",const) } GetActiveWindow() ;取激活窗口句柄 用普通方法无法获取时可用这个函数 暂时无法使用 { return DllCall("DD\DD_GetActiveWindow") } }
;预配置项 url_l = http://www.a67.com/list/1/7/p. id = 1 ;初始页码 maxid = 129 ;最大页码 url_r = site = http://www.a67.com kind = 动作片 #Include sqliteDB.ahk #NoEnv OnExit, Exit ;初始化连接数据库 以便反复查询 DBFileName := A_ScriptDir . "\a67.db" global DB DB := new SQLiteDB if !DB.OpenDB(DBFileName) { MsgBox, 16, SQLite错误, % "消息:`t" . DB.ErrorMsg . "`n代码:`t" . DB.ErrorCode ExitApp } ;首先检查初始化 if !IsObject(Query("select 1 from sqlite_master where name='movie'")) ;检查novel表 Exec("CREATE TABLE ""movie"" ( ""name"" TEXT(255), ""kind"" TEXT(255), ""uri"" TEXT(255),id"" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL)") Loop % maxid-id { list := URLDownloadToVar(url_l id url_r,"utf-8") ;抓取小说列表 a := StrSplit(list,"`n","`r") ;分割行为数组 a_id = 283 ;直接跳到正文 Loop { a_id++ if (a_id>a.MaxIndex()) break ;抓取影片信息 if (RegExMatch(a[a_id],"^<a href=""(http://www\.a67\.com/movie/\d+)""[^>]*>([^<]*)</a>$",b)) { page:=b1,name:=b2,movie_id:=RegExReplace(b1,"http://www\.a67\.com/movie/(\d+)$","$1") ToolTip % name "," movie_id "," page a_id++ t_page := URLDownloadToVar(page,"utf-8") IfInString, t_page, cqmp4 uri = cqmp4 else ifInString, t_page, hdmp4 uri = hdmp4 else ifInString, t_page, mp4-g.gif uri = mp4 else continue t_down := URLDownloadToVar("http://www.a67.com/down/1_" movie_id "_1/" uri,"utf-8") ;获取下载页的下载地址 IfInString, t_down, 404.gif continue d := StrSplit(t_down,"`n","`r") Loop % d.MaxIndex() { if RegExMatch(d[A_Index],"^\s*.*(thunder://[^""]*)"".*迅雷下载</a></li>",e) { url:=e1 ToolTip % id "页:" name Exec("Insert INTO ""movie"" (""name"", ""kind"", ""uri"") VALUES ('" name "','" kind "','" url "')") ;插入数据 break } } } } id++ } MsgBox, Ok #z:: exit: DB.CloseDB() DB = ExitApp URLDownloadToVar(url, Encoding = "",Method="GET",postData=""){ ;网址,编码,请求方式,post数据 hObject:=ComObjCreate("WinHttp.WinHttpRequest.5.1") if Method = GET { Try { hObject.Open("GET",url) hObject.Send() } catch e return -1 } else if Method = POST { Try { hObject.Open("POST",url,False) hObject.SetRequestHeader("Content-Type", "application/x-www-form-urlencoded") hObject.Send(postData) } catch e return -1 } if (Encoding && hObject.ResponseBody) { oADO := ComObjCreate("adodb.stream") oADO.Type := 1 oADO.Mode := 3 oADO.Open() oADO.Write(hObject.ResponseBody) oADO.Position := 0 oADO.Type := 2 oADO.Charset := Encoding return oADO.ReadText(), oADO.Close() } return hObject.ResponseText } ;构造查询SQL函数 Query(SQL){ ;返回数组 global DB ;全局 if !DB.GetTable(SQL, Result) MsgBox, 16, SQLite错误: 获取结果, % "消息:`t" . DB.ErrorMsg . "`n代码:`t" . DB.ErrorCode "`n" SQL if (Result.HasRows) { return Result.Rows } } ;构造执行SQL函数 Exec(SQL){ ;返回执行影响行数 global DB ;全局 if !DB.Exec(SQL) MsgBox, 16, SQLite错误: 获取结果, % "消息:`t" . DB.ErrorMsg . "`n代码:`t" . DB.ErrorCode "`n" SQL return DB._Changes() }
decodeu(ustr){ Loop { if !ustr break if RegExMatch(ustr,"^\s*\\u([A-Fa-f0-9]{2})([A-Fa-f0-9]{2})(.*)",m) { word_u := Chr("0x" m2) Chr("0x" m1), ustr := m3, word_a := "" Unicode2Ansi(word_u,word_a,0) out .= word_a } else if RegExMatch(ustr, "^([a-zA-Z0-9\.\?\-\!\s]*)(.*)",n) { ustr := n2 out .= n1 } } return out } Unicode2Ansi(ByRef wString, ByRef sString, CP = 0) { nSize := DllCall("WideCharToMultiByte" , "Uint", CP , "Uint", 0 , "Uint", &wString , "int", -1 , "Uint", 0 , "int", 0 , "Uint", 0 , "Uint", 0) VarSetCapacity(sString, nSize) DllCall("WideCharToMultiByte" , "Uint", CP , "Uint", 0 , "Uint", &wString , "int", -1 , "str", sString , "int", nSize , "Uint", 0 , "Uint", 0) }
Gui, Add, text, x0 y0 w400 h20, 要翻译的文字 Gui, Add, edit, x0 y20 w400 h180 vsrc Gui, Add, text, x400 y0 w400 h20, 结果 Gui, Add, Edit, x400 y20 w400 h180 vdst gui, Add, Button, x0 y200 w800 h20 gtrans, 翻译 gui, Show, , 翻译测试 return trans: Gui, Submit, NoHide url := "http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&smartresult=ugc" post := "type=AUTO&i=" encodeURIComponent(src) "&doctype=json&xmlVersion=1.8&keyfrom=fanyi.web&ue=UTF-8&action=FY_BY_CLICKBUTTON&typoResult=true" json := URLDownloadToVar(url,"UTF-8","POST",post) obj := json_toobj(json) if (obj.errorcode="0") { dst := obj.translateResult.1.1.tgt a := obj.smartResult.entries for k,v in a dst .= "`n" (A_Index=1 ? "智能翻译:" : Ceil(A_index-1) "." v) GuiControl, , dst, % dst } else GuiControl, , dst, % obj.errorcode return GuiClose: ExitApp json_toobj(str){ quot := """" ws := "`t`n`r " Chr(160) obj := {} objs := [] keys := [] isarrays := [] literals := [] y := nest := 0 StringGetPos, z, str, %quot% while !ErrorLevel { StringGetPos, x, str, %quot%,, % z + 1 while !ErrorLevel { StringMid, key, str, z + 2, x - z - 1 StringReplace, key, key, \\, \u005C, A If SubStr( key, 0 ) != "\" Break StringGetPos, x, str, %quot%,, % x + 1 } str := ( z ? SubStr( str, 1, z ) : "" ) quot SubStr( str, x + 2 ) StringReplace, key, key, \%quot%, %quot%, A StringReplace, key, key, \b, % Chr(08), A StringReplace, key, key, \t, % A_Tab, A StringReplace, key, key, \n, `n, A StringReplace, key, key, \f, % Chr(12), A StringReplace, key, key, \r, `r, A StringReplace, key, key, \/, /, A while y := InStr( key, "\u", 0, y + 1 ) if ( A_IsUnicode || Abs( "0x" SubStr( key, y + 2, 4 ) ) < 0x100 ) key := ( y = 1 ? "" : SubStr( key, 1, y - 1 ) ) Chr( "0x" SubStr( key, y + 2, 4 ) ) SubStr( key, y + 6 ) literals.insert(key) StringGetPos, z, str, %quot%,, % z + 1 } key := isarray := 1 Loop Parse, str, % "]}" { StringReplace, str, A_LoopField, [, [], A Loop Parse, str, % "[{" { if ( A_Index != 1 ) { objs.insert( obj ) isarrays.insert( isarray ) keys.insert( key ) obj := {} isarray := key := Asc( A_LoopField ) = 93 } if ( isarray ) { Loop Parse, A_LoopField, `,, % ws "]" if ( A_LoopField != "" ) obj[key++] := A_LoopField = quot ? literals.remove(1) : A_LoopField } else { Loop Parse, A_LoopField, `, Loop Parse, A_LoopField, :, % ws if ( A_Index = 1 ) key := A_LoopField = quot ? literals.remove(1) : A_LoopField else if ( A_Index = 2 && A_LoopField != "" ) obj[key] := A_LoopField = quot ? literals.remove(1) : A_LoopField } nest += A_Index > 1 } If !--nest Break pbj := obj obj := objs.remove() obj[key := keys.remove()] := pbj If ( isarray := isarrays.remove() ) key++ } Return obj } encodeURIComponent(p) { str:=Ansi2UTF8(p) res:=Encode(&str) return res } Encode(p) { SetFormat,integer,hex res := "" while,value := *p++ { if(value==33 || (value>=39 && value <=42) || value==45 || value ==46 || (value>=48 && value<=57) || (value>=65 && value<=90) || value==95 || (value>=97 && value<=122) || value==126) res .= Chr(value) Else { res .= "%" res .= SubStr(value,3,2) } } Return res } Ansi2UTF8(sString) { Ansi2Unicode(sString, wString, 0) Unicode2Ansi(wString, zString, 65001) Return zString } UTF82Ansi(zString) { Ansi2Unicode(zString, wString, 65001) Unicode2Ansi(wString, sString, 0) Return sString } Ansi2Unicode(ByRef sString, ByRef wString, CP = 0) { nSize := DllCall("MultiByteToWideChar" , "Uint", CP , "Uint", 0 , "Uint", &sString , "int", -1 , "Uint", 0 , "int", 0) VarSetCapacity(wString, nSize * 2) DllCall("MultiByteToWideChar" , "Uint", CP , "Uint", 0 , "Uint", &sString , "int", -1 , "Uint", &wString , "int", nSize) } Unicode2Ansi(ByRef wString, ByRef sString, CP = 0) { nSize := DllCall("WideCharToMultiByte" , "Uint", CP , "Uint", 0 , "Uint", &wString , "int", -1 , "Uint", 0 , "int", 0 , "Uint", 0 , "Uint", 0) VarSetCapacity(sString, nSize) DllCall("WideCharToMultiByte" , "Uint", CP , "Uint", 0 , "Uint", &wString , "int", -1 , "str", sString , "int", nSize , "Uint", 0 , "Uint", 0) } URLDownloadToVar(url, Encoding = "",Method="GET",postData=""){ ;网址,编码,请求方式,post数据 hObject:=ComObjCreate("WinHttp.WinHttpRequest.5.1") if Method = GET { hObject.Open("GET",url) Try hObject.Send() catch e return -1 } else if Method = POST { hObject.Open("POST",url,False) hObject.SetRequestHeader("Content-Type", "application/x-www-form-urlencoded") Try hObject.Send(postData) catch e return -1 } if Encoding { oADO := ComObjCreate("adodb.stream") oADO.Type := 1 oADO.Mode := 3 oADO.Open() oADO.Write(hObject.ResponseBody) oADO.Position := 0 oADO.Type := 2 oADO.Charset := Encoding return oADO.ReadText(), oADO.Close() } return hObject.ResponseText }
Gui, Add, text, x0 y0 w400 h20, 要翻译的文字 Gui, Add, edit, x0 y20 w400 h180 vsrc Gui, Add, text, x400 y0 w400 h20, 结果 Gui, Add, Edit, x400 y20 w400 h180 vdst gui, Add, Button, x0 y200 w800 h20 gtrans vtrans, 翻译 gui, Show, , 百度翻译测试 return trans: Gui, Submit, NoHide GuiControl, Disable, trans url := "http://fanyi.baidu.com/v2transapi" if RegExMatch(src,"[^a-zA-Z0-9\.\?\-\!\s]") slang := "zh",dlang := "en" else slang := "en",dlang := "zh" post := "from=" slang "&to=" dlang "&query=" encodeURIComponent(src) "&transtype=realtime&simple_means_flag=3" json := URLDownloadToVar(url,"UTF-8","POST",post) obj := json_toobj(json) trans_result := decodeu(obj.trans_result.data.1.dst) res := "翻译结果:`n" trans_result "`n`n" dict_result := obj.dict_result.simple_means.symbols if IsObject(dict_result.1) { res .= "词典结果:`n" for k,v in dict_result.1.parts { res .= k ". " v.part if IsObject(v.means) { for x,y in v.means { if IsObject(y) res .= decodeu(y.word_mean) ";" else res .= decodeu(y) ";" } res .= "`n" } } } if IsObject(obj.dict_result.cizu) { res .= "`n词组结果:`n" for k,v in obj.dict_result.cizu res .= k ". " decodeu(v.fanyi) "(" decodeu(v.cz_name) "):" v.jx.1.jx_en " " decodeu(v.jx.1.jx_zh) "`n" } GuiControl, , dst, % res GuiControl, Enable, trans return GuiClose: ExitApp json_toobj(str){ quot := """" ws := "`t`n`r " Chr(160) obj := {} objs := [] keys := [] isarrays := [] literals := [] y := nest := 0 StringGetPos, z, str, %quot% while !ErrorLevel { StringGetPos, x, str, %quot%,, % z + 1 while !ErrorLevel { StringMid, key, str, z + 2, x - z - 1 StringReplace, key, key, \\, \u005C, A If SubStr( key, 0 ) != "\" Break StringGetPos, x, str, %quot%,, % x + 1 } str := ( z ? SubStr( str, 1, z ) : "" ) quot SubStr( str, x + 2 ) StringReplace, key, key, \%quot%, %quot%, A StringReplace, key, key, \b, % Chr(08), A StringReplace, key, key, \t, % A_Tab, A StringReplace, key, key, \n, `n, A StringReplace, key, key, \f, % Chr(12), A StringReplace, key, key, \r, `r, A StringReplace, key, key, \/, /, A while y := InStr( key, "\u", 0, y + 1 ) if ( A_IsUnicode || Abs( "0x" SubStr( key, y + 2, 4 ) ) < 0x100 ) key := ( y = 1 ? "" : SubStr( key, 1, y - 1 ) ) Chr( "0x" SubStr( key, y + 2, 4 ) ) SubStr( key, y + 6 ) literals.insert(key) StringGetPos, z, str, %quot%,, % z + 1 } key := isarray := 1 Loop Parse, str, % "]}" { StringReplace, str, A_LoopField, [, [], A Loop Parse, str, % "[{" { if ( A_Index != 1 ) { objs.insert( obj ) isarrays.insert( isarray ) keys.insert( key ) obj := {} isarray := key := Asc( A_LoopField ) = 93 } if ( isarray ) { Loop Parse, A_LoopField, `,, % ws "]" if ( A_LoopField != "" ) obj[key++] := A_LoopField = quot ? literals.remove(1) : A_LoopField } else { Loop Parse, A_LoopField, `, Loop Parse, A_LoopField, :, % ws if ( A_Index = 1 ) key := A_LoopField = quot ? literals.remove(1) : A_LoopField else if ( A_Index = 2 && A_LoopField != "" ) obj[key] := A_LoopField = quot ? literals.remove(1) : A_LoopField } nest += A_Index > 1 } If !--nest Break pbj := obj obj := objs.remove() obj[key := keys.remove()] := pbj If ( isarray := isarrays.remove() ) key++ } Return obj } decodeu(ustr){ Loop { if !ustr break if RegExMatch(ustr,"^\s*\\u([A-Fa-f0-9]{2})([A-Fa-f0-9]{2})(.*)",m) { word_u := Chr("0x" m2) Chr("0x" m1), ustr := m3, word_a := "" Unicode2Ansi(word_u,word_a,0) out .= word_a } else if RegExMatch(ustr, "^([a-zA-Z0-9\.\?\-\!\s]*)(.*)",n) { ustr := n2 out .= n1 } } return out } encodeURIComponent(p) { str:=Ansi2UTF8(p) res:=Encode(&str) return res } Encode(p) { SetFormat,integer,hex res := "" while,value := *p++ { if(value==33 || (value>=39 && value <=42) || value==45 || value ==46 || (value>=48 && value<=57) || (value>=65 && value<=90) || value==95 || (value>=97 && value<=122) || value==126) res .= Chr(value) Else { res .= "%" res .= SubStr(value,3,2) } } SetFormat,integer, d Return res } Ansi2UTF8(sString) { Ansi2Unicode(sString, wString, 0) Unicode2Ansi(wString, zString, 65001) Return zString } UTF82Ansi(zString) { Ansi2Unicode(zString, wString, 65001) Unicode2Ansi(wString, sString, 0) Return sString } Ansi2Unicode(ByRef sString, ByRef wString, CP = 0) { nSize := DllCall("MultiByteToWideChar" , "Uint", CP , "Uint", 0 , "Uint", &sString , "int", -1 , "Uint", 0 , "int", 0) VarSetCapacity(wString, nSize * 2) DllCall("MultiByteToWideChar" , "Uint", CP , "Uint", 0 , "Uint", &sString , "int", -1 , "Uint", &wString , "int", nSize) } Unicode2Ansi(ByRef wString, ByRef sString, CP = 0) { nSize := DllCall("WideCharToMultiByte" , "Uint", CP , "Uint", 0 , "Uint", &wString , "int", -1 , "Uint", 0 , "int", 0 , "Uint", 0 , "Uint", 0) VarSetCapacity(sString, nSize) DllCall("WideCharToMultiByte" , "Uint", CP , "Uint", 0 , "Uint", &wString , "int", -1 , "str", sString , "int", nSize , "Uint", 0 , "Uint", 0) } URLDownloadToVar(url, Encoding = "",Method="GET",postData=""){ hObject:=ComObjCreate("WinHttp.WinHttpRequest.5.1") if Method = GET { hObject.Open("GET",url) Try hObject.Send() catch e return -1 } else if Method = POST { hObject.Open("POST",url,False) hObject.SetRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8") hObject.SetRequestHeader("Accept", "*/*") hObject.SetRequestHeader("Referer", "http://fanyi.baidu.com/") hObject.SetRequestHeader("X-Requested-With", "XMLHttpRequest") Try hObject.Send(postData) catch e return -1 } if Encoding { oADO := ComObjCreate("adodb.stream") oADO.Type := 1 oADO.Mode := 3 oADO.Open() oADO.Write(hObject.ResponseBody) oADO.Position := 0 oADO.Type := 2 oADO.Charset := Encoding return oADO.ReadText(), oADO.Close() } return hObject.ResponseText }
var_dump(obj,level:=0){ static id,str id++ if id=1 str := "" if IsObject(obj) { space = loop % level space .= A_Tab str .= space "{`n" for k,v in obj { if IsObject(v) { str .= space A_Tab (RegExMatch(k,"^\d+$") ? k : """" k """") ":`n" var_dump(v,level+1) str := RegExReplace(str,"(*ANYCRLF)\n$",",`n") } else str .= space A_Tab (RegExMatch(k,"^\d+$") ? k : """" k """") ":""" RegExReplace(v,"""","""""") """,`n" } str := RegExReplace(str,"(*ANYCRLF),\n*$","`n") str .= space "}`n" } else str := obj return str }
效果:
d := {"a":"animal","b":"bus","c":"cartoon","d":["door","desk","dream"]} Clipboard := var_dump(d) ;=> { "a":"animal", "b":"bus", "c":"cartoon", "d": { 1:"door", 2:"desk", 3:"dream" } }
由于对接的有个网关定期换IP,手动设定很麻烦。所以写了这么一个脚本扔到cron里。
首先需要修改/etc/asterisk/sip.conf,找到#include sip_custom.conf这里,修改成:
;#include sip_custom.conf #include sip_additional.conf #include sip_custom.conf
然后把py脚本整到/bin里:
import re import os part_a = '''[9031] disallow=all username=9031 type=friend secret=9031 qualify=yes insecure=invite host=dynamic dtmfmode=rfc2833 context=from-pstn canreinvite=0 allow=g723 [9031_Out] disallow=all username=9031 type=friend secret=9031 qualify=yes port=7878 host=''' part_b = ''' fromeuser=9031 context=from-pstn allow=g723 ''' res = os.popen('asterisk -x "sip show peers"').read() lines = res.split("\n") for line in lines: if line.find("9031/9031")>-1: inbound = re.match("9031/9031\s+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s+D\s+Yes\s+Yes\s+\d+\s+OK \(\d+ ms\)",line) elif line.find("9031_Out/9031")>-1: outbound = re.match("9031_Out/9031\s+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s+Yes\s+Yes\s+\d+\s+UNREACHABLE",line) if inbound and outbound and inbound.group(1) <> outbound.group(1): print "Change peer IP "+outbound.group(1)+" to "+inbound.group(1) f = open("\etc\asterisk\sip_custom.conf","w") f.write(part_a+inbound.group(1)+part_b) f.close() os.popen('asterisk -x reload') else: print "Peer IP has not changed"
再修改/etc/crontab,添加一个定时任务:
*/10 * * * * root python /bin/check_trunk_ip.py
最后重启下crond服务就Ok啦。
service crond restart
47 queries in 1.410 seconds |