国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術文章
文章詳情頁

Python使用paramiko連接遠程服務器執行Shell命令的實現

瀏覽:44日期:2022-06-26 13:43:20
需求

在自動化測試場景里, 有時需要在代碼里獲取遠程服務器的某些數據, 或執行一些查詢命令,如獲取Linux系統版本號 獲取CPU及內存的占用等, 本章記錄一下使用paramiko模塊SSH連接服務器的方法

1. 先安裝paramiko庫

pip3 install paramiko2. 代碼

#!/usr/bin/env python# coding=utf-8'''# :author: Terry Li# :url: https://blog.csdn.net/qq_42183962# :copyright: © 2020-present Terry Li# :motto: I believe that the God rewards the diligent.'''import paramikoclass cfg:host = '192.168.2.2'user = 'root'password = '123456'class sshChannel:def __init__(self, cfg_obj, timeout_s=5, port=22):self._cfg = cfg_objself.ssh_connect_timeout = timeout_sself.port = portself.ssh = self.connect_server()def connect_server(self):ssh_cli = paramiko.SSHClient()key = paramiko.AutoAddPolicy()ssh_cli.set_missing_host_key_policy(key)try:ssh_cli.connect(self._cfg.host, port=self.port, username=self._cfg.user, password=self._cfg.password,timeout=self.ssh_connect_timeout)except paramiko.ssh_exception.SSHException:print('連接{}失敗, 請檢查配置或重試'.format(self._cfg.host))ssh_cli.close()return ssh_clidef execute_cmd(self, cmd):''':param cmd: 單個命令:return: 服務器的輸出信息'''stdin, stdout, stderr = self.ssh.exec_command(cmd)self.ssh.close()return stdout.read().decode(’utf-8’)def execute_cmd_list(self, cmd_list):''':param cmd: 命令列表:return: 服務器的輸出信息的列表'''out_list = list(map(self.execute_cmd, cmd_list))return out_listdef test_get_sys_version(self):sys_version = self.execute_cmd('lsb_release -rd')print(sys_version)def test_get_sys_disk_free_and_memory_free(self):sys_info = self.execute_cmd_list(['df -h -BG /', 'free -m'])print(sys_info)if __name__ == ’__main__’:server = sshChannel(cfg)server.test_get_sys_version()server.test_get_sys_disk_free_and_memory_free()

到此這篇關于Python使用paramiko連接遠程服務器執行Shell命令的實現的文章就介紹到這了,更多相關Python使用paramiko連接遠程服務器執行Shell命令內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!

標簽: Python 編程
相關文章:
主站蜘蛛池模板: 横山县| 赫章县| 东乡族自治县| 福海县| 济南市| 古蔺县| 财经| 库尔勒市| 崇左市| 长乐市| 阿合奇县| 资中县| 论坛| 宝丰县| 江山市| 海林市| 高要市| 南华县| 淮安市| 会昌县| 临湘市| 城固县| 蒙自县| 林周县| 安化县| 伊金霍洛旗| 方城县| 湖州市| 麦盖提县| 贵阳市| 龙泉市| 巩留县| 吴川市| 民乐县| 枞阳县| 苏尼特右旗| 新闻| 县级市| 乌兰浩特市| 宣恩县| 江北区|