开发者社区> shadowcat> 正文

python中执行shell命令的几个方法小结

简介: 来源:http://www.jb51.net/article/55327.htm Python 执行 shell 命令 最近有个需求就是页面上执行shell命令,第一想到的就是os.system os.system('cat /proc/cpuinfo') 但是发现页面上打印的命令执行结果 0或者1,当然不满足需求了。尝试第二种方案 os.popen()output = os.
+关注继续查看


来源:http://www.jb51.net/article/55327.htm

Python 执行 shell 命令

最近有个需求就是页面上执行shell命令,第一想到的就是os.system

os.system('cat /proc/cpuinfo')
但是发现页面上打印的命令执行结果 0或者1,当然不满足需求了。
尝试第二种方案 os.popen()
output = os.popen('cat /proc/cpuinfo')
print output.read()
通过 os.popen() 返回的是 file read 的对象,对其进行读取 read() 的操作可以看到执行的输出。但是无法读取程序执行的返回值)
尝试第三种方案 commands.getstatusoutput() 一个方法就可以获得到返回值和输出,非常好用。
(status, output) = commands.getstatusoutput('cat /proc/cpuinfo')
print status, output
Python Document 中给的一个例子,
>>> import commands
>>> commands.getstatusoutput('ls /bin/ls')
(0, '/bin/ls')
>>> commands.getstatusoutput('cat /bin/junk')
(256, 'cat: /bin/junk: No such file or directory')
>>> commands.getstatusoutput('/bin/junk')
(256, 'sh: /bin/junk: not found')
>>> commands.getoutput('ls /bin/ls')
'/bin/ls'
>>> commands.getstatus('/bin/ls')
'-rwxr-xr-x 1 root 13352 Oct 14 1994 /bin/ls'

使用 paramiko 连接ssh 远程主机 执行 shell 命令

import paramiko

if __name__ == '__main__':

    ip = '172.28.11.132' 
    port = 22           
    user_name = "root"  
    user_password = r'123456' 
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    ssh.connect(ip, port, user_name, user_password)
    cmd = 'ls /'
    stdin, stdout, stderr = ssh.exec_command(cmd)
    print stdout.readlines()



版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。

相关文章
shell 清空文件方法
shell 清空文件方法
21 0
LINUX 常用替换命令三种方法(perl、shell、sed)
LINUX 常用替换命令三种方法(perl、shell、sed)
109 0
Shell运算符、$((运算式))” 或 “$[运算式]、expr方法、条件判断、test condition、[ condition ]、两个整数之间比较、按照文件权限进行判断、按照文件类型进行判断
Shell运算符、$((运算式))” 或 “$[运算式]、expr方法、条件判断、test condition、[ condition ]、两个整数之间比较、按照文件权限进行判断、按照文件类型进行判断
22 0
Shell运算符、$((运算式))” 或 “$[运算式]、expr方法、条件判断、test condition、[ condition ]、两个整数之间比较、按照文件权限进行判断、按照文件类型进行判断
多条件判断(&& 表示前一条命令执行成功时,才执行后一条命令,|| 表示上一 条命令执行失败后,才执行下一条命令)、-eq 等于(equal) -ne 不等于(not equal)-lt 小于(less than) -le 小于等于(less equal)-gt 大于(greater than) -ge 大于等于(greater equal)注:如果是字符串之间的比较 ,用等号“=”判断相等;用“!=”判断不等。 -r 有读的权限(read)-w 有写的权限(write)-x 有执行的权限(execute)
34 0
在 Linux 中更改用户 Shell 的 3 种方法
shell 是 Unix 和 Linux 操作系统中的命令行界面。它提供了一种通过发出命令和程序与操作系统交互的方式。shell 也称为命令解释器或命令处理器。
963 0
shell中的函数及脚本调试方法
shell中的函数及脚本调试方法
66 0
Linux - Shell 脚本中获取本机 ip 地址方法
Linux - Shell 脚本中获取本机 ip 地址方法
690 0
运行 Shell 脚本有两种方法
运行 Shell 脚本有两种方法
130 0
安卓无法进入adb shell 和 adb install无响应的解放方法
安卓无法进入adb shell 和 adb install无响应的解放方法
663 0
+关注
shadowcat
酱油程序猿 CSDN 博客:http://blog.csdn.net/freeking101
文章
问答
视频
文章排行榜
最热
最新
相关电子书
更多
给运维工程师的Python实战课
立即下载
Shell 脚本速查手册
立即下载
Python 脚本速查手册
立即下载