Restful接口對操作系統進行操作

  在產品開發過程中,有時候需要web端對服務器進行操作,如修改ip、重啓設備、關機等。前後端交互有很多方法,常見的有web端直接調用系統命令、通過數據庫交互和Restful接口交互。直接調用系統命令最簡單,但是最不安全,基本上沒人會使用;數據庫交互鼻尖安全,但是比較消耗硬件資源。所以Restful交互是一種很好的方式。

  下面代碼是對Restful形式交互的實現:

#-*- coding:utf-8 -*-
#!/usr/bin/env python

'''
Created on 2017.5.9
@desc: 對系統操作的模塊,負責關機、重啓、ping地址和修改網絡
@useMethord shutdown: http://127.0.0.1:7777/ins/json?Command=shutdown
@useMethord restart: http://127.0.0.1:7777/ins/json?Command=restart
@useMethord ping: http://127.0.0.1:7777/ins/json?ip=120.25.160.121
@useMethord changeNetwork: http://127.0.0.1:7777/ins/json?ip_addr="$ip"\
&gateway="$gateway"&netmask="$mask"&dns="$dns"&device="eth0"
'''

import os
import traceback
import ipaddr
import commands
import socket,sys,urllib
from BaseHTTPServer import *


class Restful(BaseHTTPRequestHandler):
    
    def __init__(self,request,client_address,server):
        BaseHTTPRequestHandler.__init__(self, request, client_address, server)
        self.dp = None
        self.router = None
        
    def basepath(self):
        pass
    
    def getresetlet(self):
        pass
    
    def send(self,src):
        """
        @desc: 返回結果的函數
        """
        try:
            self.send_response(200)
            self.send_header("Content-type", "text/html")
            self.end_headers()
            self.wfile.write(src)
            self.wfile.close()
        except:
            traceback.print_exc()
        
    def done(self):
        self.dp = self.basepath()
        self.router = self.getresetlet()
    
class doService(Restful):
    def do_GET(self):
        try:
            self.done()
            query = None
            query = urllib.splitquery(self.path)
            print self.path
            print query
            #關機
            if "Command=shutdown" in self.path:
                self.shutdown()
            #重啓
            elif "Command=restart" in self.path:
                self.restart()
            #ping地址
            elif "ip=" in self.path:
                query_string = query[1]
                print query_string
                if query_string:
                    ip = query_string.split('=')[1]
                    self.ping(ip)
                else:
                    self.send('False')
            #修改網絡參數
            else:
                paramsInput=['ip_addr','netmask','gateway','dns','device']
                for pInput in paramsInput:
                    if self.path.find(pInput) < 0:
                        self.send('False')
                        return
                param=query[1].split('&')
                pdict={}
                for p in param:
                    tmp=p.split('=')
                    pdict[tmp[0]]=tmp[1]
                print 'change network success...'
                res = self.changeNetwork(pdict['ip_addr'], pdict['gateway'],
                                         pdict['netmask'],pdict['dns'], pdict['device'])
                if res:
                    self.send("True")
                else:
                    self.send("False")
        except:
            traceback.print_exc()
            self.send("False")
        
    def basepath(self):
        return "/ins"
    
    def shutdown(self):
        try:
            os.system("sudo init 0")
            print "power off success..."
            self.send("True")
        except:
            traceback.print_exc()
            self.send("False")
    
    def restart(self):
        try:
            os.system("sudo init 6")
            print "restart success..."
            self.send("True")
        except:
            traceback.print_exc()
            self.send("False")
    
    def ping(self,ip):
        try:
            if ip:
                ipaddr.IPAddress(ip)
                output = commands.getoutput("ping %s -c 4"%ip)
                if "100% packet loss" in output:
                    self.send("False")
                else:
                    self.send("True")
        except:
            traceback.print_exc()
            self.send("False")
            
    def changeNetwork(self,ip,gateway,mask,dns,device):
        try:
            if ip and gateway and mask and dns and device:
                ipaddr.IPAddress(ip)
                if ip == "1.1.1.1":
                    self.send("please change another ip...")
                    return False
                else:
                    try:
                        files = open("/etc/network/interfaces", 'r')
                        interface_content=files.read()
                        files.close()
                        net_split_contents = interface_content.split("########") #8個
                        for data in net_split_contents:
                            if device in data:
                                content = """\nauto %s\niface %s inet static\n    address %s\n    netmask %s\n    gateway %s\n    dns-nameservers %s\n\n""" %(device,device,ip,mask,gateway,dns)
                                interface_content=interface_content.replace(data,content)
                                break
                        files = open("/etc/network/interfaces", 'w+')
                        files.write(interface_content)
                        files.close()
                        result = commands.getoutput("sudo ifdown %s && sudo ifup %s" %(device,device))
                        if "Failed" in result:
                            return False
                        else:
                            return True
                    except:
                        traceback.print_exc()
                        return False
        except:
            traceback.print_exc()
            return False

def main():          
    try:
        server=HTTPServer(('127.0.0.1',7777),doService)
        server.serve_forever()
    except KeyboardInterrupt:
        sys.exit(0)

if __name__ == "__main__":
    main()

  運行上面的代碼,會監控本機的7777端口,只要監控到相應的命令就會執行相應的動作。web端只需要吧相應的操作發送到777端口即可。


參考:http://www.cnblogs.com/wuchaofan/p/3432596.html

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