python:执行dos命令、Linux命令

在实际开发中,有时为了方便,可能需要执行dos命令或者Linux命令。比如说执行某些shell脚本,上传下载一些文件,执行adb命令等跨语言,加压包,解压包等跨操作系统的场景。这样能大大加强多个平台和操作系统之间的关联性。

windows:

案例1:弹窗式执行dos命令(与打开cmd执行一模一样)

# -*- coding: utf-8 -*-
import os

# 解决打印时,部分中文乱码问题
os.popen('chcp 65001')

# 查看当前路径
command1 = "chdir"
os.system(command1)

# 查看 ip
command2 = "ipconfig"
os.system(command2)

案例2:后台执行
# -*- coding: utf-8 -*-
import os
# 后台执行 adb命令
command2 = "adb"
os.popen(command2)

案例3:执行多条dos命令
# -*- coding: utf-8 -*-
import os

# command1执行成功,才往下执行command2
command1 = "java -version"
command2 = "adb version"

# 使用 && 隔开。
command = "{} && {}".format(command1, command2)
print(command)
os.popen(command)

Linux:

Linux操作系统下,Python需要安装一个第三方模块:

pip install paramiko

图片

案例1:执行单条linux命令 - 方法:execute_cmd()
案例2:执行多条linux命令 - 方法:execute_cmd_list()

# coding=utf-8
import paramiko


class ServerMessage:
    # 目标服务器信息
    host = "xxx.xxx.xxx.xxx"
    user = "root"
    password = "xxxxxxxx"


class SshChannel:
    def __init__(self, cfg_obj, timeout_sec=15, port=22):
        self._cfg = cfg_obj
        self.ssh_connect_timeout = timeout_sec
        self.port = port
        self.ssh_cli = None

    def __enter__(self):
        try:
            self.connecting_server_with_SSH2()
        except paramiko.ssh_exception.SSHException:
            print("连接{}失败, 请核实配置或重试".format(self._cfg.host))
            self.ssh_cli.close()
        else:
            return self

    def __exit__(self, tp, value, trace):
        self.ssh_cli.close()

    def connecting_server_with_SSH2(self):
        self.ssh_cli = paramiko.SSHClient()
        self.ssh_cli.load_system_host_keys()

        key = paramiko.AutoAddPolicy()
        self.ssh_cli.set_missing_host_key_policy(key)
        self.ssh_cli.connect(self._cfg.host, port=self.port, username=self._cfg.user, password=self._cfg.password,
                             timeout=self.ssh_connect_timeout)

    def execute_cmd(self, cmd, get_pty=False):
        """
        :param cmd: 单个命令
        :return: 服务器的输出信息
        """

        stdin, stdout, stderr = self.ssh_cli.exec_command(cmd, get_pty)
        return stdout.read().decode('utf-8')

    def execute_cmd_list(self, cmd_list):
        """
        :param cmd: 单个命令
        :return: 服务器的输出信息
        """
        # 英文模式下的分号隔开。" ; "
        cmd = "".join([i + " ; " for i in cmd_list])

        stdin, stdout, stderr = self.ssh_cli.exec_command(cmd, get_pty=True)
        return stdout.read().decode('utf-8')


if __name__ == '__main__':
    with SshChannel(ServerMessage) as my_server:
        # 调用单条命令演示
        pwd1 = my_server.execute_cmd("pwd")
        print(pwd1)
        
        # 调用多条命令演示
        pwd2 = my_server.execute_cmd_list(["pwd", "free -m"])
        print(pwd2)

微信公众号:玩转测试开发
欢迎关注,共同进步,谢谢!

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值