博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python os.system()和os.popen()
阅读量:4170 次
发布时间:2019-05-26

本文共 2079 字,大约阅读时间需要 6 分钟。

1》python调用Shell脚本,有两种方法:os.system()和os.popen(),
前者返回值是脚本的
退出状态码,后者的返回值是脚本执行过程中的
输出内容。
>>>help(os.system)
Help on built-in function system in module posix:
system(...)
    system(command) -> exit_status
    Execute the command (a string) in a subshell.
>>> help(os.popen)
Help on built-in function popen in module posix:
popen(...)
    popen(command [, mode='r' [, bufsize]]) -> pipe
    Open a pipe to/from a command returning a file object.
2》假定有一个shell脚本test.sh:
song@ubuntu:~$ vi test.sh
song@ubuntu:~$ more test.sh
#!/bin/bash
echo 'hello python!'
echo 'hello world!'
exit 1
song@ubuntu:~$ 
2.1》os.system(command):该方法在调用完shell脚本后,返回一个16位的二进制数,
低位为杀死所调用脚本的信号号码,
高位为脚本的退出状态码
即脚本中“exit 1”的代码执行后,os.system函数返回值的高位数则是1,如果低位数是0的情况下,
则函数的返回值是0x0100,换算为十进制得到256。
要获得os.system的正确返回值,可以
使用位移运算(将返回值右移8位)还原返回值
>>> import os
>>> os.system("./test.sh")
hello python!
hello world!
256
>>> n=os.system("./test.sh")
hello python!
hello world!
>>> n
256
>>> n>>8
1
>>> 
2.2》os.popen(command):这种调用方式是通过
管道的方式来实现,函数
返回一个file对象
里面的内容是脚本输出的内容(可简单理解为echo输出的内容),使用os.popen调用test.sh的情况:
>> import os
>>> os.popen("./test.sh")
<open file './test.sh', mode 'r' at 0x7f6cbbbee4b0>
>>> f=os.popen("./test.sh")
>>> f
<open file './test.sh', mode 'r' at 0x7f6cbbbee540>
>>> f.readlines()
['hello python!\n', 'hello world!\n']
>>> 
3》像调用”ls”这样的shell命令,应该使用popen的方法来获得内容,对比如下:
>>> import os
>>> os.system("ls")   #
直接看到运行结果
Desktop    Downloads
    Music     Public
     Templates  Videos
Documents  examples.desktop  Pictures  systemExit.py  test.sh
0    #返回值为0,表示命令执行成功
>>> n=os.system('ls')
Desktop    Downloads
    Music     Public
     Templates  Videos
Documents  examples.desktop  Pictures  systemExit.py  test.sh
>>> n
0
>>> n>>8   #将返回值右移8位,得到正确的返回值
0
>>> f=os.popen('ls') #
返回一个file对象,可以对这个文件对象进行相关的操作
>>> f
<open file 'ls', mode 'r' at 0x7f5303d124b0>
>>> f.readlines()
['Desktop\n', 'Documents\n', 'Downloads\n', 'examples.desktop\n', 'Music\n', 'Pictures\n', 'Public\n', 'systemExit.py\n', 'Templates\n', 'test.sh\n', 'Videos\n']
>>> 
总结:os.popen()可以实现一个“管道”,从这个命令获取的值可以继续被使用。因为它返回一个文件对象,可以对这个文件对象进行相关的操作。

但是如果要直接看到运行结果的话,那就应该使用os.system,用了以后,立竿见影!

友情链接:

1》 

2》 

转载地址:http://tjyai.baihongyu.com/

你可能感兴趣的文章
为逃避检测而取消持久性:KPOT v2.0信息窃取恶意软件分析
查看>>
《Lateral Movement — SCM and DLL Hijacking Primer》的利用扩展
查看>>
为逃避检测而取消持久性:KPOT v2.0信息窃取恶意软件分析
查看>>
ScarCruft APT组织开发针对蓝牙的恶意软件
查看>>
抢地盘?两大黑客组织就Linux服务器展开激烈角逐
查看>>
Windows Hello认证推进无密码认证
查看>>
发公告说被关了?认真你就输了
查看>>
CVE-2019-0708漏洞影响面分析及采用多种规则的检测方法
查看>>
拿走不谢!固件逆向分析过程中的工具和技巧(上)
查看>>
整理网络安全措施的5个小技巧
查看>>
原来Java反序列化远程执行漏洞这么简单
查看>>
移动应用安全基础篇——解密iOS加密数据
查看>>
针对国内IP发起攻击的DDoS样本分析
查看>>
入侵win10(下)--渗透系统
查看>>
Linux主机安全检查与应急响应
查看>>
关于Metasploit 5中测试模块的移植与验证
查看>>
GoMet:Go编写的多平台Agent和控制器
查看>>
CVE-2019-11815:Linux kernel漏洞
查看>>
剥丝抽茧,层层破解!看我如何一步步绕过防火墙直至获取你的支付卡信息
查看>>
CVE-2019-0708漏洞: RDP= Really DO Patch?
查看>>