網站首頁 編程語言 正文
在實際開發中,有時為了方便,可能需要執行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)
原文鏈接:https://mp.weixin.qq.com/s/jnlCFx6O2oPXzYMywVso_Q
相關推薦
- 2023-01-20 Python輸入圓半徑,計算圓周長和面積的實現方式_python
- 2022-03-27 C#?Razor語法規則_C#教程
- 2022-12-05 Django中QuerySet查詢優化之prefetch_related詳解_python
- 2022-07-24 C語言與C++中關于字符串使用的比較_C 語言
- 2023-02-05 如何用C#獲取計算機詳細的軟件和硬件信息_C#教程
- 2022-03-30 Android?Jetpack?Compose無限加載列表_Android
- 2022-10-26 Go?語言數據結構之雙鏈表學習教程_Golang
- 2022-09-08 pytorch中函數tensor.numpy()的數據類型解析_python
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支