• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

Python使用paramiko连接远程服务器执行Shell命令的实现

python 搞代码 4年前 (2022-01-07) 13次浏览 已收录 0个评论
文章目录[隐藏]

这篇文章主要介绍了Python使用paramiko连接远程服务器执行Shell命令的实现,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

需求

自动化测试场景里, 有时需要在代码里获取远程服务器的某些数据, 或执行一些查询命令,如获取Linux系统版本号 \ 获取CPU及内存的占用等, 本章记录一下使用paramiko模块SSH连接服务器的方法

1. 先安装paramiko库

 pip3 install paramiko

2. 代码

 #!/usr/bin/env python # coding=utf-8 """ # :author: Terry Li # :url: https://blog.gaodaimna/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: 服务器的输出信息 """ stdin, stdout, stderr = self.ssh.exec_command(cmd) self.ssh.close() return stdout.read().decode('utf-8') def execute_cmd_list(self, cmd_list): <div style="color:transparent">来源gaodai.ma#com搞##代!^码网</div>""" :param cmd: 命令列表 :return: 服务器的输出信息的列表 """ 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()

到此这篇关于Python使用paramiko连接远程服务器执行Shell命令的实现的文章就介绍到这了,更多相关Python使用paramiko连接远程服务器执行Shell命令内容请搜索gaodaima搞代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持gaodaima搞代码网

以上就是Python使用paramiko连接远程服务器执行Shell命令的实现的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Python使用paramiko连接远程服务器执行Shell命令的实现
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址