首页 > 代码库 > Restful接口对操作系统进行操作

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

本文出自 “黑色时间” 博客,请务必保留此出处http://blacktime.blog.51cto.com/11722918/1924166

Restful接口对操作系统进行操作