{% extends "index.html" %}
{% block page_css %}
{% endblock %}
{% block page_title %}
执行脚本
{% endblock %}
{% block container %}
{% load staticfiles %}
$(function () {
$('#backup_all').click(function () {
var socket = new WebSocket("ws://" + window.location.host + "/app01/echo_once/");
socket.onopen = function () {
console.log('WebSocket open');//成功连接上Websocket
socket.send($('#backup_all').val());//发送数据到服务端
};
socket.onmessage = function (e) {
console.log('message: ' + e.data);//打印服务端返回的数据
$('#messagecontainer').prepend('
' + e.data + '');
$('#messagecontainer').prepend('
');
};
});
});
执行脚本
脚本执行结果:
{% endblock %}
views中的配置:
def exec_command(comm):
hostname = smart_str('192.168.1.195')
username = smart_str('xxxxxx')
password = smart_str('******')
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=hostname, username=username, password=password,allow_agent=False,look_for_keys=False)
stdin, stdout, stderr = ssh.exec_command(comm)
result = stdout.read()
ssh.close()
return result
@accept_websocket
def echo_once(request):
if not request.is_websocket():
print "这里实现wbsocket连接逻辑"
try:
message = request.GET['message']
return HttpResponse(message)
except:
return render(request, 'test3.html')
else:
for message in request.websocket:
message = message.decode('utf-8')
if message == 'backup_all':
command = 'sh test2.sh'
request.websocket.send(exec_command(command))
else:
request.websocket.send('小样儿,没权限!!!'.encode('utf-8'))
# @accept_websocket
# def echo(request):
# if request.is_websocket:#如果是webvsocket
# lock = threading.RLock() #rlock线程锁
# try:
# lock.acquire()#抢占资源
# clients.append(request.websocket)#把websocket加入到clients
# print(clients)
# for message in request.websocket:
# if not message:
# break
# for client in clients:
# client.send(message)
# finally:
# clients.remove(request.websocket)
# lock.release()#释放锁
文档:http://www.cnblogs.com/huguodong/p/6611602.html