Xterm是一個基於X Window System的終端模擬器(Terminal Emulator)。Xterm最初由MIT開發,它允許使用者在X Window環境下執行文字終端程式。Xterm提供了一個圖形介面終端,使使用者能夠在圖形桌面環境中執行命令列程式。而xterm.js是一個用於在瀏覽器中實現終端模擬的JavaScript庫。它允許在Web頁面中建立互動式的終端介面,使用者可以在瀏覽器中執行命令列程式,執行命令,並與終端進行互動。
主要特點和功能包括:
xterm.js通常被用於Web應用程式中,尤其是在需要提供命令列介面的場景下,如線上終端、遠端伺服器管理等。這使得開發者能夠在瀏覽器中實現類似於本地終端的互動體驗,而無需使用本地終端模擬器。
AJAX(Asynchronous JavaScript and XML)是一種用於在Web應用程式中實現非同步資料交換的技術。它允許在不重新載入整個頁面的情況下,通過在後臺與伺服器進行小規模的資料交換,實現動態更新網頁內容的目的。AJAX廣泛用於建立互動性強、使用者體驗良好的Web應用程式,例如在載入新資料、進行表單驗證、實現自動完成搜尋等方面。
如下前端部分,通過使用ajax
向後端提交資料,當success:function
接收到資料後直接將資料動態回寫到Xterm
終端上,程式碼如下所示;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="https://www.lyshark.com/javascript/xterm/xterm.css" />
<script type="text/javascript" src="https://www.lyshark.com/javascript/xterm/xterm.js"></script>
<script type="text/javascript" src="https://www.lyshark.com/javascript/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
var window_width = $(window).width()-200;
var window_height = $(window).height()-300;
var term = new Terminal(
{
cols: Math.floor(window_width/9),
rows: Math.floor(window_height/20),
useStyle:false,
convertEol: true,
cursorBlink:false,
cursorStyle:null,
rendererType: "canvas",
}
);
term.open(document.getElementById('terminal'));
function show(){
var address = $("#address").val();
var command = $("#command").val();
console.log(command);
$.ajax({
url:"/",
type:"POST",
contentType:"application/json;",
data: JSON.stringify({"address":address,"command":command}),
success:function (res)
{
// term.clear();
term.writeln( "\x1B[1;3;33m IP地址: \x1B[0m" + res.address );
term.writeln( "\x1B[1;3;34m 命令: \x1B[0m" + res.command );
}
});
}
</script>
<!--提交資料-->
<div id="terminal"></div>
<input type="text" id="address" placeholder="主機地址"/>
<input type="text" id="command" placeholder="執行命令"/>
<input type="button" value="執行命令" onclick="show()">
</div>
</body>
</html>
後端部分的實現很簡單,首先封裝一個ssh_shell
用於執行命令,使用者傳入資料後,直接執行並將返回結果放入到ref內即可。
from flask import Flask,render_template,request
from flask import jsonify
import paramiko
app = Flask(__name__)
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
def ssh_shell(address,username,password,port,command):
ssh.connect(address,port=port,username=username,password=password)
stdin, stdout, stderr = ssh.exec_command(command)
result = stdout.read()
if not result:
result=stderr.read()
ssh.close()
return result.decode()
@app.route('/', methods=[ 'GET', 'POST'])
def index():
if request.method == "POST":
# 接收資料
json_value = request.get_json()
ref = ssh_shell("192.168.150.128","root","123123","22",json_value["command"])
# 傳送資料
info = dict()
info["address"] = json_value["address"]
info["command"] = ref
return jsonify(info)
else:
return render_template("index.html")
if __name__ == '__main__':
app.run()
繼續擴充套件將編輯框去掉,使用者輸入資料後直接傳入到Xterm內,Xterm裡賣弄判斷如果出現了回車,則像後端傳送ajax資料,否則繼續偵聽並記下輸入資料。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="https://www.lyshark.com/javascript/xterm/xterm.css" />
<script type="text/javascript" src="https://www.lyshark.com/javascript/xterm/xterm.js"></script>
<script type="text/javascript" src="https://www.lyshark.com/javascript/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<div id="terminal"></div>
<script type="text/javascript">
var window_width = $(window).width()-500;
var window_height = $(window).height()-300;
var term = new Terminal
(
{
cols: Math.floor(window_width/9),
rows: Math.floor(window_height/20),
useStyle:false,
convertEol: true,
cursorBlink: true, //遊標閃爍
cursorStyle: "underline", //遊標樣式
rendererType: "canvas",
}
);
term.open(document.getElementById('terminal'));
term.writeln("welcome to lyshark web terminal!");
term.write("[shell] # ");
let input = '';
term.on('key', (key, ev) => {
let code = key.charCodeAt(0);
console.log(code);
// 如果按下回車,則傳送命令,並等待輸出結果
if(code == 13)
{
term.write("\r\n");
$.ajax({
url:"/",
type:"POST",
contentType:"application/json;",
data: JSON.stringify({"command": input}),
success:function (res)
{
term.write(res.value);
}
});
input ='';
}
// 如果是退格,則清除
else if(code == 127)
{
term.write("\b");
}
else
{
input += key
term.write(key);
}
});
</script>
</body>
</html>
後端收到資料後解析命令,比對命令是否存在,根據不同的命令執行不同的分支。
from flask import Flask,render_template,request
from flask import jsonify
app = Flask(__name__)
@app.route('/', methods=[ 'GET', 'POST'])
def index():
if request.method == "POST":
# 接收資料
json_value = request.get_json()["command"]
if len(json_value) != 0:
# 判斷使用哪一個分支
splite_value = json_value.split(" ")
info = dict()
if splite_value[0] == "help":
info["value"] = "version 1.0"
info["value"] = info["value"] + "\n[shell] # "
return jsonify(info)
elif splite_value[0] == "GetCPU":
address = splite_value[1]
info["value"] = "192.168.1 CPU 10%"
info["value"] = info["value"] + "\n[shell] # "
return jsonify(info)
else:
info["value"] = "命令不存在"
info["value"] = info["value"] + "\n[shell] # "
return jsonify(info)
else:
info = dict()
info["value"] = "[shell] # "
return jsonify(info)
else:
return render_template("index.html")
if __name__ == '__main__':
app.run()
執行後可輸出一個互動式WebShell環境,如下圖所示;
雖然WebSSH可以方便管理主機,但如果需要批次運維則需要開發一個可以多條訊息共同推播的命令列。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="https://www.lyshark.com/javascript/xterm/xterm.css" />
<script type="text/javascript" src="https://www.lyshark.com/javascript/xterm/xterm.js"></script>
<script type="text/javascript" src="https://www.lyshark.com/javascript/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript" src="https://www.lyshark.com/javascript/socket.io/socket.io.min.js"></script>
</head>
<body>
<div id="terminal"></div>
<script type="text/javascript" charset="UTF-8">
$(document).ready(function()
{
namespace = '/Socket';
var socket = io.connect("http://" + document.domain + ":" + location.port + namespace);
var window_width = $(window).width()-500;
var window_height = $(window).height()-300;
var term = new Terminal
(
{
cols: Math.floor(window_width/9),
rows: Math.floor(window_height/20),
useStyle:false,
convertEol: true,
cursorBlink: true,
rendererType: "canvas",
}
);
// 開啟Web終端
term.open(document.getElementById('terminal'));
term.write("[shell] # ");
let input_command = '';
term.on('key', (key, ev) => {
let code = key.charCodeAt(0);
console.log(code);
// 如果按下回車,則傳送命令,並等待輸出結果
if(code == 13)
{
// 傳送資料到後端
term.write("\r\n");
socket.emit("message",{"command": input_command});
input_command ='';
}
// 如果是退格,則清除
else if(code == 127)
{
term.write("\b");
}
else
{
input_command += key
term.write(key);
}
});
// 接受後臺返回並輸出
socket.on('response', function(recv)
{
console.log(recv.value);
term.write(recv.value);
});
});
</script>
</body>
</html>
後臺接收引數,並更具不同的引數執行不同的運維函數,此處只做演示,具體功能需要自行編寫。
from flask import Flask,render_template,request
from flask_socketio import SocketIO
async_mode = None
app = Flask(__name__)
app.config['SECRET_KEY'] = "lyshark"
socketio = SocketIO(app)
@app.route("/")
def index():
return render_template("index.html")
# 出現訊息後,率先執行此處
@socketio.on("message",namespace="/Socket")
def socket(message):
print("接收到訊息:",message['command'])
command = message['command']
if len(command) != 0:
splite_command = command.split(" ")
if splite_command[0] == "help":
socketio.emit("response", {"value": "version 1.0 \n"}, namespace="/Socket")
elif splite_command[0] == "Ping":
if len(splite_command) == 2:
index = splite_command[1]
for each in range(int(index)):
socketio.sleep(0.1)
socketio.emit("response",{"value": str(each) + "\n"}, namespace="/Socket")
socketio.emit("response", {"value": "\n[shell] # "}, namespace="/Socket")
else:
socketio.emit("response", {"value": "lyShell: command not found \n"}, namespace="/Socket")
else:
socketio.emit("response", {"value": "[shell] # "}, namespace="/Socket")
# 當websocket連線成功時,自動觸發connect預設方法
@socketio.on("connect",namespace="/Socket")
def connect():
print("連結建立成功..")
# 當websocket連線失敗時,自動觸發disconnect預設方法
@socketio.on("disconnect",namespace="/Socket")
def disconnect():
print("連結建立失敗..")
if __name__ == '__main__':
socketio.run(app,debug=True)
Socket版本的將會更流暢,如下圖所示;