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)
【推荐】FlashTable:表单开发界的极速跑车,让你的开发效率一路狂飙
【推荐】Flutter适配HarmonyOS 5知识地图,实战解析+高频避坑指南
【推荐】博客园的心动:当一群程序员决定开源共建一个真诚相亲平台
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步