zoukankan      html  css  js  c++  java
  • python 运行CMD和shell命令

    1. 方法1 os.system【切换目录等不适用】
    #有状态码,无返回值
    import os
    
    os.system('taskkill /F /IM node.exe 2>nul')
    
    1. 方法2 subprocess
    # 功能最强
    import subprocess
    import shlex
    
    def runCommand(cmd):
        output = subprocess.Popen(shlex.split(cmd), stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
        # rst = output.stdout.read()  # .decode("UTF8").strip()
        rst = output.stdout.readlines()  # .decode("UTF8").strip()
        return rst
    
    cmd = 'shutdown -s -t 90'
    rst = runCommand(cmd)
    
    
    
    # subprocess 文档
    https://segmentfault.com/a/1190000020660715
    #下面的用法是等价的
    output = subprocess.Popen(['ping','1.1.1.1'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    stdout = output.stdout.read()
    print(stdout.decode("gbk"))
    
    child = subprocess.Popen(['ping','1.1.1.1'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    stdout, stderr = child.communicate()
    print(stdout.decode("gbk"))
    
    
    
    1. 方法3 ssh
    bat = 'cmd.exe /c "if exist "' + dir + '" (echo y) else (echo n)"'
    # print(bat.encode("gbk"))
    # exit(000)
    # 如果执行的命令中带有中文,需要将bat命令进行encode编码加密处理
    stdin, stdout, stderr = ssh.exec_command(bat.encode("gbk"))
    result = stdout.read().decode("gbk")
    # print(result)
    if result.strip() == 'y':
        print("\033[0;32m%s\033[0m" % "目录存在!")
    else:
        print("\033[0;31m%s\033[0m" % "目录不存在!")
    return
    
    
    # 使用手册
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())    #指定当对方主机没有本机公钥的情况时应该怎么办,AutoAddPolicy表示自动在对方主机保存下本机的秘钥
    ssh.connect('ip',22,'user','passwd')    #SSH端口默认22,可改
    stdin,stdout,stderr = ssh.exec_command("命令内容")    #这三个得到的都是类文件对象
    outmsg,errmsg = stdout.read(),stderr.read()    #读一次之后,stdout和stderr里就没有内容了,所以一定要用变量把它们带的信息给保存下来,否则read一次之后就没有了
    if errmsg == "":
        print outmsg
    if errmsg == b"":  # window 下
        print (outmsg.decode('gbk'))
    ssh.close()
    
    1. 方法4 commands
    # 有状态码,返回值
    import commands
    
    status = commands.getstatus('cat /etc/passwd')
    print(status)
    output = commands.getoutput('cat /etc/passwd')
    print(output)
    (status, output) = commands.getstatusoutput('cat /etc/passwd')
    print(status, output)
    
    1. 方法5 os.popen
    # 有状态码,返回值
    import os
    result = os.popen('cat /etc/passwd')
    print(result.read())
    
  • 相关阅读:
    Linux Shell系列教程之(十七) Shell文件包含
    Linux Shell系列教程之(十六) Shell输入输出重定向
    Linux Shell系列教程之(十五) Shell函数简介
    Linux Shell系列教程之(十四) Shell Select教程
    Linux Shell系列教程之(十三)Shell分支语句case … esac教程
    Linux Shell系列教程之(十二)Shell until循环
    Linux Shell系列教程
    算法系列:链表
    C++ 系列:Boost Thread 编程指南
    C++:多线程002
  • 原文地址:https://www.cnblogs.com/amize/p/13669070.html
Copyright © 2011-2022 走看看