python调用Linux命令

方法一、os模块

使用os.popen(),该方法以文件的形式返回shell指令运行后的结果,需要获取内容时可使用read()或readlines()方法

import os
ip="hostname -I | awk '{print $1}'"
internet_ip=os.popen(ip).read() #获取命令执行结果是字符串,该字符串有换行
internet_ip=os.popen(ip).read().split("\n")[0] #获取一个没有换行的字符串


方法二、subprocess模块
import subprocess

ubuntu_name="root"
ip_ubuntu="192.168.1.111"
cmd_name="ip a"

call函数

   #推荐使用这个

subprocess.call("ssh %s@%s ls -la"%(ubuntu_name,ip_ubuntu),shell=True)

subprocess模块的Popen类

f=subprocess.Popen("ssh %s@%s ls -la"%(ubuntu_name,ip_ubuntu),shell=True,stdout=subprocess.PIPE,universal_newlines=True)
for i in f.stdout.readlines():
print(i)



posted @ 2021-07-22 19:26  梁博客  阅读(998)  评论(0)    收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示