xshell調用js腳本開發

轉載請註明出處:https://blog.csdn.net/xuezoutianya

在編寫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();
}

運行腳本的操作:

實際執行結果如下:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章