在实际开发中,有时为了方便,可能需要执行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需要安装一个第三方模块:

案例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)