python3模拟实现xshell远程执行liunx命令的方法

yipeiwu_com7年前Python基础

依赖包:pip install paramiko

源码demo:

from time import *
import paramiko
# 定义一个类,表示一台远端linux主机
class Linux(object):
  # 通过IP, 用户名,密码,超时时间初始化一个远程Linux主机
  def __init__(self, ip, username, password, timeout=30):
    self.ip = ip
    self.username = username
    self.password = password
    self.timeout = timeout
    # transport和chanel
    self.t = ''
    self.chan = ''
    # 链接失败的重试次数
    self.try_times = 3
 
  # 调用该方法连接远程主机
  def connect(self):
    while True:
      # 连接过程中可能会抛出异常,比如网络不通、链接超时
      try:
        self.t = paramiko.Transport(sock=(self.ip, 22))
        self.t.connect(username=self.username, password=self.password)
        self.chan = self.t.open_session()
        self.chan.settimeout(self.timeout)
        self.chan.get_pty()
        self.chan.invoke_shell()
        # 如果没有抛出异常说明连接成功,直接返回
        print('连接%s成功' % self.ip)
        # 接收到的网络数据解码为str
        print(self.chan.recv(65535).decode('utf-8'))
        return
      # 这里不对可能的异常如socket.error, socket.timeout细化,直接一网打尽
      except Exception as e1:
        if self.try_times != 0:
          print('连接%s失败,进行重试' % self.ip)
          self.try_times -= 1
        else:
          print('重试3次失败,结束程序')
          exit(1)
 
  # 断开连接
  def close(self):
    self.chan.close()
    self.t.close()
 
  # 发送要执行的命令
  def send(self, cmd):
    cmd += '\r'
    result = ''
    # 发送要执行的命令
    self.chan.send(cmd)
    # 回显很长的命令可能执行较久,通过循环分批次取回回显,执行成功返回true,失败返回false
    while True:
      sleep(0.5)
      ret = self.chan.recv(65535)
      ret = ret.decode('utf-8')
      result += ret
      return result
  '''
  发送文件
  @:param upload_files上传文件路径 例如:/tmp/test.py
  @:param upload_path 上传到目标路径 例如:/tmp/test_new.py
  '''
  def upload_file(self,upload_files,upload_path):
    try:
      tran=paramiko.Transport(sock=(self.ip, self.port))
      tran.connect(username=self.username, password=self.password)
      sftp = paramiko.SFTPClient.from_transport(tran)
      result=sftp.put(upload_files, upload_path)
      return True if result else False
    except Exception as ex:
      print(ex)
      tran.close()
    finally:
      tran.close()
 
 
# 连接正常的情况
if __name__ == '__main__':
  host = Linux('192.168.16.57', 'root', '+B*A15*EFpKG') # 传入Ip,用户名,密码
  host.connect()
  # result = host.send('ls') # 发送一个查看ip的命令
  def input_cmd(str):
    return input(str)
  tishi_msg="输入命令:"
  while True:
    msg=input(tishi_msg)
    if msg=="exit":
      host.close()
      break
    else:
      res=host.send(msg)
      data=res.replace(res.split("\n")[-1],"")
      tishi_msg=res.split("\n")[-1]
      print(res.split("\n")[-1] + data.strip("\n"))

运行代码测试效果图:

以上这篇python3模拟实现xshell远程执行liunx命令的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python实现生成字符串大小写字母和数字的各种组合

1 输出大写字母、小写字母、大小写字母、数字、大小写字母和数字 1.1输出小写:找到小写a(97)到z(122)的的ASCII码,然后转义为字母 lower = "" for i i...

Python3.5 + sklearn利用SVM自动识别字母验证码方法示例

Python3.5 + sklearn利用SVM自动识别字母验证码方法示例

前言 最近正在研究人工智能,为了加深对算法的理解,决定写个自动设别验证码的程序。看了看网上的demo,大部分都是python2的写法,而且验证码的识别都是用的数字做例子,那我就写个基于p...

纯Python开发的nosql数据库CodernityDB介绍和使用实例

纯Python开发的nosql数据库CodernityDB介绍和使用实例

看看这个logo,有些像python的小蛇吧 。这次介绍的数据库codernityDB是纯python开发的。 先前用了下tinyDB这个本地数据库,也在一个api服务中用了下,一开始...

Python实现遍历目录的方法【测试可用】

Python实现遍历目录的方法【测试可用】

本文实例讲述了Python实现遍历目录的方法。分享给大家供大家参考,具体如下: # *-* coding=gb2312 *-* import os.path import shuti...

Python3.4实现从HTTP代理网站批量获取代理并筛选的方法示例

本文实例讲述了Python3.4实现从HTTP代理网站批量获取代理并筛选的方法。分享给大家供大家参考,具体如下: 最近在写爬虫,苦于不采用代理的情况下,默认的IP不出几分钟就被封了,故而...