#!/usr/bin/python3 import os import sys curPath = os.path.abspath(os.path.dirname(__file__)) rootPath = os.path.split(curPath)[0] sys.path.append(rootPath) import subprocess from src import logutils def run(): log=logutils.logger("app",rootstdout=True,handlerList=[‘I‘,‘E‘]) str_shell=‘df -m && netstat -ntlp‘ sub=subprocess.Popen(args=str_shell,shell=True,stdin=subprocess.PIPE,stdout=subprocess.PIPE, stderr=subprocess.PIPE,universal_newlines=True) out,err=sub.communicate() log.info(type(out)) log.info(out,exc_info=True) if __name__ == ‘__main__‘: run()
[root@hostuser src]# python3 subprocess_popen.py [INFO]2019-05-18 23:39:07 Sat --app-- subprocess_popen.py: <class ‘str‘> [INFO]2019-05-18 23:39:07 Sat --app-- subprocess_popen.py: Filesystem 1M-blocks Used Available Use% Mounted on /dev/mapper/centos-root 27627 8627 19000 32% / devtmpfs 894 0 894 0% /dev tmpfs 910 1 910 1% /dev/shm tmpfs 910 11 900 2% /run tmpfs 910 0 910 0% /sys/fs/cgroup /dev/sda1 1014 232 783 23% /boot tmpfs 182 1 182 1% /run/user/42 tmpfs 182 0 182 0% /run/user/0 Active Internet connections (only servers) Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name tcp 0 0 127.0.0.1:9100 0.0.0.0:* LISTEN 6481/node_exporter tcp 0 0 0.0.0.0:111 0.0.0.0:* LISTEN 1/systemd tcp 0 0 127.0.0.1:8080 0.0.0.0:* LISTEN 7057/unicorn master tcp 0 0 127.0.0.1:9168 0.0.0.0:* LISTEN 6505/ruby tcp 0 0 192.168.122.1:53 0.0.0.0:* LISTEN 9232/dnsmasq tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 7211/sshd tcp 0 0 127.0.0.1:631 0.0.0.0:* LISTEN 7212/cupsd tcp 0 0 127.0.0.1:25 0.0.0.0:* LISTEN 7459/master tcp 0 0 127.0.0.1:6010 0.0.0.0:* LISTEN 52237/sshd: root@pt tcp 0 0 127.0.0.1:6011 0.0.0.0:* LISTEN 57561/sshd: root@pt tcp 0 0 0.0.0.0:8060 0.0.0.0:* LISTEN 6479/nginx: master tcp 0 0 0.0.0.0:8989 0.0.0.0:* LISTEN 6479/nginx: master tcp 0 0 127.0.0.1:9121 0.0.0.0:* LISTEN 6485/redis_exporter tcp 0 0 127.0.0.1:9090 0.0.0.0:* LISTEN 6472/prometheus tcp 0 0 127.0.0.1:9187 0.0.0.0:* LISTEN 6494/postgres_expor tcp6 0 0 :::111 :::* LISTEN 1/systemd tcp6 0 0 ::1:9168 :::* LISTEN 6505/ruby tcp6 0 0 :::22 :::* LISTEN 7211/sshd tcp6 0 0 :::23 :::* LISTEN 35527/xinetd tcp6 0 0 ::1:631 :::* LISTEN 7212/cupsd tcp6 0 0 ::1:25 :::* LISTEN 7459/master tcp6 0 0 ::1:6010 :::* LISTEN 52237/sshd: root@pt tcp6 0 0 ::1:6011 :::* LISTEN 57561/sshd: root@pt NoneType: None [root@hostuser src]#
原文:https://www.cnblogs.com/SunshineKimi/p/10887744.html