技术标签: linux 下python flask
I was trying to build a web-based utility for Linux Management and I found those are not familiar to me with which Node.js, ShellJS, ... etc. Luckily I found another way to control the underlying Linux system in python, simply put, the flask web framework plus the python subprocess module would work.
Simple demo code
import subprocess
from flask import Flask
app = Flask(__name__)
def run_command(command):
return subprocess.Popen(command, shell=True, stdout=subprocess.PIPE).stdout.read()
@app.route('/')
def command_server(command):
return run_command(command)
$ export FLASK_APP=server.py
$ flask run
image.png
The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. This module intends to replace several older modules and functions
os.system
os.spawn*
Difference between Popen and os.system call
os.system is equivalent to Unix system command, while subprocess was a helper module created to provide many of the facilities provided by the Popen commands with an easier and controllable interface. Those were designed similar to the Unix Popen command.
system() executes a command specified in command by calling /bin/sh -c command, and returns after the command has been completed
The popen() function opens a process by creating a pipe, forking, and invoking the shell.
subprocess.popen vs subprocess.run
subprocess.run was added in Python 3.5 as a simplification over subprocess.Popen when you just want to execute a command and wait until it finishes, but you don't want to do anything else meanwhile. For other cases, you still need to use subprocess.Popen.
The main difference is that subprocess.run executes a command and waits for it to finish, while with subprocess.Popen you can continue doing your stuff while the process finishes and then just repeatedly call subprocess.communicate yourself to pass and receive data to your process.
Note that, what subprocess.run is actually doing is invoking for you the Popen and communicate, so you don't need to make a loop to pass/receive data nor wait for the process to finish.
Check the official documentation for information of which parameters of subprocess.run are passed to Popen and which to communicate.
Complete code demo from run shell command with flask gist
from flask import Flask
from flask import request
import subprocess
app = Flask('flaskshell')
ip_whitelist = ['192.168.1.2', '192.168.1.3']
query_success = "SELECT COUNT(*) FROM flasktest.tasks WHERE task_status='Success'"
query_pending = "SELECT COUNT(*) FROM flasktest.tasks WHERE task_status='Pending'"
query_failed = "SELECT COUNT(*) FROM flasktest.tasks WHERE task_status='Failed'"
def valid_ip():
client = request.remote_addr
if client in ip_whitelist:
return True
else:
return False
@app.route('/status/')
def get_status():
if valid_ip():
command_success = "mysql -uflaskuser -pflask123 -e '{0}'".format(
query_success)
command_pending = "mysql -uflaskuser -pflask123 -e '{0}'".format(
query_pending)
command_failed = "mysql -uflaskuser -pflask123 -e '{0}'".format(
query_failed)
try:
result_success = subprocess.check_output(
[command_success], shell=True)
result_pending = subprocess.check_output(
[command_pending], shell=True)
result_failed = subprocess.check_output(
[command_failed], shell=True)
except subprocess.CalledProcessError as e:
return "An error occurred while trying to fetch task status updates."
return 'Success %s, Pending %s, Failed %s' % (result_success, result_pending, result_failed)
else:
return """
404 Not FoundThe requested URL was not found on the server.
If you entered the URL manually please check your
spelling and try again.
""", 404if __name__ == '__main__':
app.run()
窝的第一篇博客第一篇博客随便说点啥叭 阿巴阿巴阿巴之前也没有尝试写过题解之类的,也没有这个习惯,主要是平时比赛和训练的代码都很丑 平时也没有整理总结的习惯,但是最近写的题对我来说基本都是新学的算法,基本上一周补一题或者两题,感觉还是应该记录一下的,方便以后查看,所以还是写写博客题解什么的记录一下叭。啾咪~...
Container 容器注:在使用框架时,需要获得容器才可对其进行内部内容操作。常用方法:1. Add()//添加组件2. setLayout()//设置布局管理器3. remove() //删除组件
使用bat删除发现没删除成功,原因是路径中有中文Pause.bat文件里面的内容:del /s /q /f D:\学习\批处理\教程.pdf解决方法:bat文件默认的编码是utf-8, 需要将编码改为ANSI编码。本地是通过notepad++修改的:改好之后直接双击bat文件,删除成功。...
1、创建分区表hive> create table weather_list(year int,data int) partitioned by (createtime string,area string) row format delimited fields terminated by ",";修改表:hive> alter table w...
Atitit.线程 死锁 跑飞 的检测与自动解除 与手动解除死锁 java c# .net php javascript. 1. 现象::主程序卡住无反应,多行任务不往下执行 12. 原因::使用jv jprofile查看线程,原来俩个线程死锁了。。 13. Java的缺点,默认不能自动解除死锁 14. 自动检测与解除死锁::使用看门狗watchdog 24.1. 死锁检
SQL> alter database open;alter database open*第 1 行出现错误:ORA-16038: 日志 1 序列号 2554 无法归档ORA-19809: 超出了恢复文件数的限制ORA-00312: 联机日志 1 线程 1: 'D:\DISK3\REDO01A.LOG'ORA-00312: 联机日志 1 线程 1: 'D:\DISK6\REDO01B
运行如下几种方法:str = "www.Baidu.com"print(str.upper()) # 把所有字符中的小写字母转换成大写字母print(str.lower()) # 把所有字符中的大写字母转换成小写字母print(str.capitalize()) # 把第一个字母转化为大写字母,其余小写print(str.title()) # 把每个单词的第一个字母转化为大写,其余小写 输出结果为:...
http://www.blogjava.net/amigoxie/archive/2011/12/14/303038.html#366367在上两篇写WebService的文章中: 1)使用XFire+Spring构建Web Service(一)——helloWorld篇 2)使用XFire+Spring构建Web Service(二) 讲到了如何使用XFir...
在springboot项目整合mybatis的时候,添加通用Mapper插件tk.mybatis,然后出现报错,错误信息:说是找不到方法什么的,在找了很多资料后得出原因是:tk.mybatis会自动引用依赖引入persistence-api-1.0.jar包,而persistence-api-1.0.jar的PersistenceUnitInfo类中并没有getValidationMo...
1, 对于一个国家来说,数据库的建设规模,数据库信息量的大小和使用频度已成为衡量这个国家信息化程度的一个重要标志。2, 数据系统的几个重要概念(1) 数据:数据是数据库中储存的基本对象。描述事物的符号记录称为数据,它可以是数字,也可以是文字,图形,图像,声音,语言等多种表现形式,它们都可以经过数字化后存入计算机。数据的表现形式还不能完全表达其内容,需要经过解释,数据和关于数据的解
今天想在LaTeX插入代码,高亮显示,网上基本上都建议使用listings宏包,但是试用了一下,发现效果一般。后来发现了另一个叫minted的宏包,使用简单,效果好,c++的效果如下:但是需要安装很多东西,下面整理一下安装流程。我的环境是win7-64bit,已经安装了CTeX套装,平时使用WinEdt来编辑(就是如何在WinEdt上添加命令行参数困扰了我半天)。