在自動化測試
場景里, 有時需要在代碼里獲取遠(yuǎn)程服務(wù)器的某些數(shù)據(jù), 或執(zhí)行一些查詢命令,如獲取Linux系統(tǒng)版本號 \ 獲取CPU及內(nèi)存的占用等, 本章記錄一下使用paramiko模塊SSH連接服務(wù)器的方法
pip3 install paramiko
#!/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 paramiko class 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_obj self.ssh_connect_timeout = timeout_s self.port = port self.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_cli def execute_cmd(self, cmd): """ :param cmd: 單個命令 :return: 服務(wù)器的輸出信息 """ 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: 服務(wù)器的輸出信息的列表 """ out_list = list(map(self.execute_cmd, cmd_list)) return out_list def 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()
到此這篇關(guān)于Python使用paramiko連接遠(yuǎn)程服務(wù)器執(zhí)行Shell命令的實現(xiàn)的文章就介紹到這了,更多相關(guān)Python使用paramiko連接遠(yuǎn)程服務(wù)器執(zhí)行Shell命令內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
標(biāo)簽:文山 錫林郭勒盟 懷化 昆明 浙江 西寧 石家莊 梅州
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《Python使用paramiko連接遠(yuǎn)程服務(wù)器執(zhí)行Shell命令的實現(xiàn)》,本文關(guān)鍵詞 Python,使用,paramiko,連接,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。