在实际开发中,有时为了方便,可能需要执行DOS命令或者linux命令。比如说执行某些shell脚本,上传下载一些文件,执行adb命令等跨语言,加压包,解压包等跨操作系统的场景。这样能大大加强多个平台和操作系统之间的关联性
在实际开发中,有时为了方便,可能需要执行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("连接{}失败cting_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)
到此这篇关于Python执行dos和Linux命令的方法详解的文章就介绍到这了,更多相关Python执行dos Linux命令内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!
--结束END--
本文标题: Python执行dos和Linux命令的方法详解
本文链接: https://www.lsjlt.com/news/34368.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0