xshell呼叫js指令碼開發
阿新 • • 發佈:2019-02-02
在編寫xshell指令碼的過程中用到最多的就是自動輸入,自動捕獲,延時等語句
自動輸入
以自動輸入xyz為例
自動輸入的語句:xsh.Screen.Send("xyz");
當然,如果你輸入的是一條命令,還需要下面這一行輸入回車
輸入回車的語句:xsh.Screen.Send(String.fromCharCode(13));
自動捕獲
以linux系統為例,一般程式執行的列印資料位於倒數第二行,如下圖所示
/* 字串處理 */
var ScreenRow, ReadLine, Items;
/* 讀取倒數第二行,長度為40個字元 */
ScreenRow = xsh.Screen.CurrentRow - 1;
ReadLine = xsh.Screen.Get(ScreenRow, 1, ScreenRow, 40);
延時
以等待1s為例
延時語句:xsh.Session.Sleep(1000);
其他
開啟新會話:xsh.Session.Open(string);
對話方塊提醒:xsh.Dialog.MsgBox(string);
設定日誌路徑:xsh.Session.LogFilePath = string;
開始記錄日誌:xsh.Session.StartLog();
清屏函式:xsh.Screen.Clear();
等待輸入:xsh.Screen.WaitForString(string);
示例
本文以一個自動測試指令碼為例,定時向/tmp/test檔案寫入資料,然後回讀列印,截獲回讀列印的值進行分析
/* 測試函式 */ function test() { /* 傳送echo 112233 > /tmp/testfile */ xsh.Screen.Send("echo 112233 > /tmp/testfile"); xsh.Screen.Send(String.fromCharCode(13)); /* 傳送cat /tmp/testfile */ xsh.Screen.Send("cat /tmp/testfile"); xsh.Screen.Send(String.fromCharCode(13)); /* 字串處理 */ var ScreenRow, ReadLine, Items; /* 讀取末行的40個字元 */ ScreenRow = xsh.Screen.CurrentRow - 1; ReadLine = xsh.Screen.Get(ScreenRow, 1, ScreenRow, 40); /* 如果讀取到的字元不是112233 */ if(ReadLine != "112233") { /* 會話框列印實際的字串 */ xsh.Dialog.MsgBox(ReadLine); } } /* 主函式 */ function Main() { /* 開啟會話,根據實際的會話路徑修改 */ xsh.Session.Open("C:\Users\Administrator\Documents\NetSarang Computer\6\Xshell\Sessions\ubuntu.xsh"); xsh.Screen.Synchronous = true; /* 開始記錄日誌 */ xsh.Session.LogFilePath = "C:\Users\Administrator\Documents\NetSarang Computer\6\Xshell\Logs\example.log"; xsh.Session.StartLog(); /* 等待輸入start */ // xsh.Screen.WaitForString("start"); /* 傳送rm -rf /tmp/testfile */ xsh.Screen.Send("rm -rf /tmp/testfile"); /* 傳送回車 */ xsh.Screen.Send(String.fromCharCode(13)); /* 傳送touch /tmp/testfile */ xsh.Screen.Send("touch /tmp/testfile"); xsh.Screen.Send(String.fromCharCode(13)); /* 測試100次 */ for(var i = 1; i < 100; i++) { test(); xsh.Session.Sleep(500); } /* 清屏 */ // xsh.Screen.Clear(); }
執行指令碼的操作:
實際執行結果如下: